开发者

ASP.NET MVC 3 - Select Items Using Check Boxes

开发者 https://www.devze.com 2023-03-09 15:03 出处:网络
I\'ve got an MVC 3 application with a page where users can request more information about our service.

I've got an MVC 3 application with a page where users can request more information about our service.

When the user selects their state from a dropdown list, I want to use jQuery ajax to fetch a list of Products we offer in that state. For each Product, I'd like to display a check box next to the Product name. Then the user can select which Products they are interested in.

I'd like to bind the selected Produ开发者_如何学Pythoncts to a List property on the model for this view. So the model will have a property for name, email, etc. and a List property. Here's an example of the model class I'm trying to bind to:

public class RequestInformationModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public List<Product> Products { get; set; }
}

Here is the controller method I will post the form to:

public ActionResult RequestInformation(RequestInformationModel model)
{
    // do stuff
}

Any advice on how to accomplish this? Thanks very much.


If you prefix the name of the fields in your product object with the name of the list and their index in square brackets, then MVC will bind the list for you

E.g.

<input type="checkbox" name="Products[0].InterestedInCheckbox" />
<input type="checkbox" name="Products[1].InterestedInCheckbox" />

In this case the Product object needs a bool property called InterestedInCheckbox

You should have sequencial indexes starting at 0 for this method to work (you would need a hidden field and a slightly different technique if this is not the case)

Finally, I'd use the Html Checkbox helper for creating the checkboxes since this will output a hidden field after the checkboxes required:

(following code is untested)

@for (var i = 0; i < Model.Count; i++)
{
    @Html.CheckBox(string.Format("Products[{0}]", i), Model[i])
}


I think what you want is something like this:

/* Handles ajax request */
[HttpPost]
public ContentResult(string selectedListBoxItem)
{
  string content = "";

  /* TODO: Query DB to get product suggestions based on selectedListBoxItem */

  content = "<input type='checkbox' id='productId1' name='productSuggestion' value='productId1'>";
  content += "<input type='checkbox' id='productId2' name='productSuggestion' value='productId2'>";
  content += "<input type='checkbox' id='productId2' name='productSuggestion' value='productId2'>";
  return Content(content);
}

 /* Handles final submit */
[HttpPost]
public ActionResult HandleSubmit(string nameOfCheckboxCollection)
{
  string[] arrayChecked = nameOfCheckboxCollection.Split(",");
  foreach(string s in arrayChecked ) { 
      Model.addProduct(s); 
   } 
}
0

精彩评论

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