How to handle `PartialRender` Models?

2020-03-07 08:19发布

问题:

if by any means I happen to have

public class DoorsModel
{
    public DoorsModel() { }

    public HttpPostedFileBase Image { get; set; }
    public String DoorLayout { get; set; }
    public bool ReplicateSettings { get; set; }
    public List<DoorDesignModel> Doors { get; set; }
}

public class DoorDesignModel
{
    public DoorDesignModel() { }

    public HttpPostedFileBase FrontFile { get; set; }
    public HttpPostedFileBase BorderFile { get; set; }
}

and in my View I have a normal form to populate the Model Properties but the List<DoorDesignModel> I'm using a User Control and use

<%Html.RenderPartial("DoorDesign", Model.Doors); %>

inside DoorDesign.ascx I have:

<%@ Control 
       Language="C#" AutoEventWireup="true"
       Inherits="System.Web.Mvc.ViewUserControl<List<MyProject.Backend.Models.DoorDesignModel>>" %>

to display all form I have a for clause

MyProject.Backend.Models.DoorDesignModel field;
for (i = 0; i < Model.Count; i++) { 
    field = Model[i];
    ... 
}

and I'm using the HTML

<input type="file" value="Upload file" 
    name="Doors.FrontFile[<%: i %>]" id="Doors.FrontFile[<%: i %>]">

but soon I press the submit button, my model returns a null List :( and I'm creating and setting a new list when starting the View as

public ActionResult Doors()
{
    DoorsModel model = new DoorsModel();

    model.Doors = new List<DoorDesignModel>();
    for (int i= 1; i<= 24; i++) // Add 24 Doors
        model.Doors.Add(new DoorDesignModel());

    return View(model);
}

[HttpPost]
public ActionResult Doors(DoorsModel model)
{
    // model.Doors is always null !!!

    if (ModelState.IsValid)
        ViewData["General-post"] = "Valid";
    else
        ViewData["General-post"] = "NOT Valid";

    return View(model);
}

What do I need to have in order to return the Doors List from the RenderPartial part?

a simple mockup of the View

回答1:

Just had the same problem. Found this website: http://weblogs.asp.net/nmarun/archive/2010/03/13/asp-net-mvc-2-model-binding-for-a-collection.aspx

Essentially it is all about <input type="file" value="Upload file" name="Doors[<%: i %>].FrontFile" id="Doors[<%: i %>].FrontFile">