首页 > 解决方案 > MVC父子模态文件上传问题

问题描述

我有一个用于获取标题详细数据的父子场景。这是我的代码,问题是当我使用文件上传时它不起作用

Person模型:

public class Person
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }

    [Display(Name = "First Name")]
    [Required]
    [StringLength(255, MinimumLength = 3)]
    public string Name { get; set; }

    [Display(Name = "Last Name")]
    [Required]
    [StringLength(255, MinimumLength = 3)]
    public string  Surname { get; set; }

    public virtual ICollection<Address> Addresses { get; set; }

    [Required(AllowEmptyStrings = false, ErrorMessage = "Error: Must Choose a Country")]
    [Range(1, int.MaxValue, ErrorMessage = "Select a Country")]
    public int CountryID { get; set; }
    public virtual Country Country { get; set; }

}

Address模型:

public class Address
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }

    [Required(AllowEmptyStrings = false, ErrorMessage = "Error: Must Choose a City")]
    [Range(1, int.MaxValue, ErrorMessage = "Select a City")]
    public int CityID { get; set; }
    public virtual City City { get; set; }

    [Required]
    [Display(Name = "Street Address")]
    public string Street { get; set; }

    [Required]
    [DataType(DataType.ImageUrl)]
    public string ImageUrl { get; set; }

    [NotMapped]
    [DataType(DataType.Upload)]
    public HttpPostedFileBase ImageUpload { get; set; }

    [Required]
    [Phone]
    public string Phone { get; set; }

    public int PersonID { get; set; }
    public virtual Person Person  { get; set; }
}

PeopleController

private DataDb db = new DataDb();

// GET: People
public async Task<ActionResult> Index()
{
    return View(await db.People.ToListAsync());
}

// GET: People/Details/5
public async Task<ActionResult> Details(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Person person = await db.People.Where(p => p.Id == id).Include(p => p.Addresses).SingleAsync();
    if (person == null)
    {
        return HttpNotFound();
    }
    return View(person);
}


// GET: People/Edit/5
public async Task<ActionResult> Edit(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    var person = await db.People
                .Include(p => p.Addresses)
                .Where(p => p.Id == id)
                .SingleAsync();

    if (person == null)
    {
        return HttpNotFound();
    }

    ViewBag.CountryID = new SelectList(db.Country, "CountryID", "CountryName", person.CountryID);
    return View(person);
}

// POST: People/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for 
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit( Person person)
{
    if (ModelState.IsValid)
    {
        db.Entry(person).State = EntityState.Modified;
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    ViewBag.CountryID = new SelectList(db.Country, "CountryID", "CountryName", person.CountryID);

    return View(person);
}

// GET: People/Delete/5
public async Task<ActionResult> Delete(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Person person = await db.People.FindAsync(id);
    if (person == null)
    {
        return HttpNotFound();
    }
    return View(person);
}

// POST: People/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
    Person person = await db.People.FindAsync(id);
    db.People.Remove(person);
    await db.SaveChangesAsync();
    return RedirectToAction("Index");
}

Address控制器:

private DataDb db = new DataDb();


public ActionResult Index(int id)
{
    ViewBag.PersonID = id;
    var addresses = db.Addresses.Where(a => a.PersonID == id).OrderBy(a => a.City.CityName);

    return PartialView("_Index", addresses.ToList());
}

[ChildActionOnly]
public ActionResult List(int id)
{
    ViewBag.PersonID = id;
    var addresses = db.Addresses.Where(a => a.PersonID == id);

    return PartialView("_List", addresses.ToList());
}

public ActionResult Create(int PersonID)
{
    //Address address = new Address();
    //address.PersonID = PersonID;
    //FillCity(address);

    Address adv = new Address();
    adv.PersonID = PersonID;
    FillCityModel(adv);

    return PartialView("_Create", adv);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Address address, HttpPostedFileBase file)
{
    if (ModelState.IsValid)
    {
        int addressID = clsStatic.newAddressID();
        address.Id = addressID;


        var uploadDir = "~/images";
        var imagePath = Path.Combine(Server.MapPath(uploadDir), address.ImageUpload.FileName);
        var imageUrl = Path.Combine(uploadDir, address.ImageUpload.FileName);
        address.ImageUpload.SaveAs(imagePath);
        address.ImageUrl = imageUrl;

        db.Addresses.Add(address);
        db.SaveChanges();


        string url = Url.Action("Index", "Addresses", new { id = address.PersonID });
        return Json(new { success = true, url = url });
    }
    FillCity(address);
    return PartialView("_Create", address);
}

public ActionResult Edit(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Address address = db.Addresses.Find(id);
    if (address == null)
    {
        return HttpNotFound();
    }
    //ViewBag.CityID = new SelectList(db.City, "CityID", "CityName", address.CityID);
    FillCity(address);
    return PartialView("_Edit", address);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Address address )
{
    var uploadDir = "~/images";
    if (address.ImageUpload != null)
    {
        var imagePath = Path.Combine(Server.MapPath(uploadDir), address.ImageUpload.FileName);
        var imageUrl = Path.Combine(uploadDir, address.ImageUpload.FileName);
        address.ImageUpload.SaveAs(imagePath);
        address.ImageUrl = imageUrl;
    }
    if (ModelState.IsValid)
    {
        db.Entry(address).State = EntityState.Modified;
        db.SaveChanges();

        string url = Url.Action("Index", "Addresses", new { id = address.PersonID });
        return Json(new { success = true, url = url });
    }

    //var file = Request.Files[0];
    //if (file != null && file.ContentLength > 0)
    //{
    //    var fileName = address.Id + Path.GetExtension(file.FileName);
    //    var path = Path.Combine(Server.MapPath("~/Images/Addresses/"), fileName);
    //    file.SaveAs(path);
    //}

    FillCity(address);

    //ViewBag.CityID = new SelectList(db.City, "CityID", "CityName", address.CityID);
    return PartialView("_Edit", address);
}

private void FillCity(Address address)
{
    List<SelectListItem> city = new List<SelectListItem>();

    foreach (City item in db.City)
    {
        if (item.CityID != address.CityID)
            city.Add(new SelectListItem { Text = item.CityName, Value = item.CityID.ToString() });
        else
            city.Add(new SelectListItem { Text = item.CityName, Value = item.CityID.ToString(), Selected = true });
    }

    ViewBag.CityID = city;
}

private void FillCityModel(Address address)
{
    List<SelectListItem> city = new List<SelectListItem>();

    foreach (City item in db.City)
    {
        if (item.CityID != address.CityID)
            city.Add(new SelectListItem { Text = item.CityName, Value = item.CityID.ToString() });
        else
            city.Add(new SelectListItem { Text = item.CityName, Value = item.CityID.ToString(), Selected = true });
    }

    ViewBag.CityID = city;
}

public ActionResult Delete(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Address address = db.Addresses.Find(id);
    if (address == null)
    {
        return HttpNotFound();
    }
    return PartialView("_Delete", address);
}

[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
    Address address = db.Addresses.Find(id);
    db.Addresses.Remove(address);
    db.SaveChanges();

    string url = Url.Action("Index", "Addresses", new { id = address.PersonID });
    return Json(new { success = true, url = url });

}

在这里_Edit查看地址我想要文件上传字段

@model TestAjax.Models.Address
<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h4 class="modal-title" id="myModalLabel">Edit Address</h4>
</div>

<div class="modal-body">
    @using (Html.BeginForm("Edit", "Addresses", FormMethod.Post,
        new { id = "editForm", enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()
        @Html.HiddenFor(model => model.PersonID)

        <div class="form-horizontal">
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            @Html.HiddenFor(model => model.Id)

            <div class="form-group">
                @Html.LabelFor(model => model.CityID, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownListFor(model => model.CityID, (List<System.Web.Mvc.SelectListItem>)ViewBag.CityID, new { @class = "form-control selectpicker" })
                    @Html.ValidationMessageFor(model => model.CityID, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Street, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Street, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Street, "", new { @class = "text-danger" })
                </div>
            </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
                        </div>
                </div>

                <div class="editor-field">
                    @Html.LabelFor(m => m.ImageUpload)
                    @Html.TextBoxFor(m => m.ImageUpload, new { type = "file" })
                </div>

            </div>
            <button class="btn" type="button" data-dismiss="modal">Cancel</button>
            <input class="btn btn-primary" type="submit" value="Save" />
        }
    </div>
    <div class="modal-footer">
    Footer
</div>


<script>
    $(document).ready(function () {
        refill();
    });

    function refill() {
        var id = @Model.CityID;
        $('#CityID').val(id);
    }
</script>

但是当我在地址控制器编辑操作中按下保存按钮时,我没有选择文件。请帮忙。

下载源代码

标签: c#asp.net-mvcmodel-view-controllerparent-childmaster-detail

解决方案


推荐阅读