开发者

Retrieving postback from Dynamically created controls in MVC without using FormCollection

I'm passing a List to an MVC view and generat开发者_运维百科ing checkboxes for each object in the list (The checkboxes are named t.Name).

I'd like to be able to tell which checkboxes were checked once the form is posted. However, I'd like to avoid using the FormCollection object. Is there any way to do this?


Set the name of your checkboxes to something like "MyObject[" + index + "].Checked", and for each checkbox also put a hidden input field named something like "MyObject[" + index + "].Name" with the value set to t.Name.

If you name your fields like that, the default model binder can take your form values and map them to a list of objects with a Name property and a Checked property.

I would try something like the following:

<% foreach(var t in Model)
{ %>
    <div>
        <%= Html.Hidden("MyObject[" + index + "].Name", t.Name, new { id = "MyObject_" + index + "_Name" }) %>
        <%= Html.Checkbox("MyObject[" + index + "].Checked", false, new { id = "MyObject_" + index + "_Checked" }) %>
    </div><%
} %>

I use the anonymous type with id property so that the MVC framework components don't generate HTML elements with invalid id values, but it isn't really necessary.

Your action handling the post would look something like this:

[HttpPost]
ActionResult MyAction(IList<MyObject> objects)
{
    foreach (MyObject obj in objects)
    {
        if (obj.Checked)
        {
            // ...
        }
        else
        {
            // ...
        }
    }

    return View();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜