How do I return List or Collection to Controller from View in MVC 3?

前端 未结 1 1464
死守一世寂寞
死守一世寂寞 2020-12-17 21:28

Someone please help me return this list properly from my view. I don\'t see why I\'m returning null for my fieldModelList I try to pass to the controller...

Here is

相关标签:
1条回答
  • 2020-12-17 21:46

    Phil Haack wrote an article some time ago explaining how to bind collections (ICollection) to view models. It goes into additional detail about creating an editor template, which you could certainly do as well.

    Basically, you need to prefix the HTML elements' name attributes with an index.

    <input type="text" name="[0].PropertyName" value="Curious George" />
    <input type="text" name="[0].PropertyValue" value="H.A. Rey" />
    
    <input type="text" name="[1].PropertyName" value="Ender's Game" />
    <input type="text" name="[1].PropertyValue" value="Orson Scott Card" />
    

    Then, your controller could bind the collection of FieldModel

    [HttpPost]
    public ActionResult GetResponse(List<FieldModel> fieldModelList)
    {
        return GetResponse(fieldModelList);   
    }
    

    I'm not 100% sure the following would name the attributes correctly (I'd recommend using the editor template) but you could easily use the htmlAttributes argument and give it a name using the index.

    @for(int i = 0;i < Model.Count;i++) 
    {
        <tr>
            <td>
                @Html.DisplayFor(m => m[i].PropertyName)
            </td>
            <td>
                @Html.TextBoxFor(m => m[i].PropertyValue)
            </td>
        </tr>
    }
    

    Editor Template

    If you wanted to go as far as adding an editor template, add a partial view named FieldModel.ascx to /Views/Shared that is strongly typed to a FieldModel

    @model Regions.SOA.UI.CopyBookSchemaCreator.Models.FieldModel
    
    @Html.TextBoxFor(m => m.PropertyName) @* This might be a label? *@
    @Html.TextBoxFor(m => m.PropertyValue)
    

    And, then the part of your view responsible for rendering the collection would look like:

    @for (int i = 0; i < Model.Count; i++) { 
        @Html.EditorFor(m => m[i]);
    }
    
    0 讨论(0)
提交回复
热议问题