Retrieving postback from Dynamically created controls in MVC without using FormCollection

≯℡__Kan透↙ 提交于 2019-12-10 12:17:55

问题


I'm passing a List to an MVC view and generating 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?


回答1:


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


来源:https://stackoverflow.com/questions/2968846/retrieving-postback-from-dynamically-created-controls-in-mvc-without-using-formc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!