Model binding to list in MVC

2019-07-04 15:47发布

问题:

I am not able to retrieve a simple list on server side. Could anyone please point me in the right direction?

public class TestList
{
    public string id { get; set; }
    public string name { get; set; }
    public string location { get; set; }
}

Form:

@model List<SampleMVC4App.Controllers.TestList>
@{
    ViewBag.Title = "Index";
}
<h2>
    Index</h2>
@using (Html.BeginForm())
{           
    <input name="cust" value="1" type="hidden" />
    <input name="[1].id" value="de107502-284d-459b-80a1-762ce0860cd8" type="hidden" />    
    <input name="[1].name" value="test1" type="hidden" />    
    <input name="[1].location" value="location1" type="hidden" />    
    <a id="AddAnother" href="#">Add</a>
    <input type="submit" value="submit" />
}

Controller:

[HttpPost]
public ActionResult Edit(ICollection<TestList> cust) **<---Null**
{
   return View();
}

回答1:

After working for hours, I managed to work it out by changing below

<input name="cust" value="1" type="hidden" />

to

<input name="Index" value="1" type="hidden" />


回答2:

Try this. your model is right . in the cshtml page try this

 @model List<SampleMVC4App.Controllers.TestList>
    @{
        ViewBag.Title = "Index";
    }
    <h2>
        Index</h2>
    @using (Html.BeginForm())
    {           
        foreach(SampleMVC4App.Controllers.TestList tl in Model)
{
     @model.hiddenfieldfor () // Like this your list will be rendered.
}
    }


回答3:

Try using Edit(FormCollection fm) to get all the form elements from the view. Then handle the returned variables in your httpPost action. That would make it easier to debug when seeing what elements are returned.

I found this post by Scott Allen to be helpful when I was working with HttpPOST http://odetocode.com/blogs/scott/archive/2009/04/27/6-tips-for-asp-net-mvc-model-binding.aspx