开发者

ASP.Net MVC - Passing selected data from View to Controller (Help!)

I have a model (entity class) Newsletter. I pass a list of Newsletter to a View and display the list of Newsletter in a table with each Newsletter across a ro开发者_开发百科w. Besides each Newsletter row, there is a checkbox. I will select the Newsletters that I want to send by checking the checkbox and clicking on a send button.

How can I pass the selected Newsletters to the controller?

Thanks.


In your view:

<input type="checkbox" name="newsletterIds" value="<%=newsletter.Id%>"/>

In your target controller:

public ActionResult SendNewsletters(int[] newsletterIds)
{
 ... do something with the ids...
}


Do something like this in your view:

<%= Html.CheckBox("cbNewColors", true) %><label for="cbNewColors">New colors</label>

in your controller, do something like this:

bool bChecked = form["cbNewColors"].Contains("true");


Simply add a boolean value called Selected to your entity class which, when passed back to the controller, will tell the controller which newsletters were selected in your list.

If you don't want to "pollute" your entity class with client metadata, you could inherit from it and add the selected bool in your derived class.

Alternatively your model can simply contain a separate list that holds references to selected newsletters or some unique identifier with which individual newsletters can later be selected from an original list.


You'll have to do some manual work, since MVC adds hidden fields for each checkbox, and relies on the model binder to deal with the value true,false coming in from the form submission (if the box was checked).

Assuming you have unique IDs available in your views, I'd recommend the following:

  1. Manually create the checkboxes (i.e. don't use the Html helper) with the same name

    < input type="checkbox" name="newsletters" value="nl_[id]" id="nl_[id]" />[name]< /label>

  2. Accept a string[] newsletters parameter into your action that handles the post. (You may need to accept a string, and then split it on commas, I don't remember array newslettersArray = newsletters.Split(','); ;)

  3. Convert the string into a list of newsletter IDs doing something like this:

    var ids = newsletters.Select(n => int.Parse(n.Substring(2)).ToList();

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜