Sunny
Sunny

Reputation: 4809

Model binding to list in MVC

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();
}

Upvotes: 3

Views: 4725

Answers (3)

user1006544
user1006544

Reputation: 1524

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.
}
    }

Upvotes: 1

Sunny
Sunny

Reputation: 4809

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" />

Upvotes: 2

Ammar
Ammar

Reputation: 1068

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

Upvotes: 0

Related Questions