开发者

Passing View Model to ASP.NET MVC 3 Edit Controller

开发者 https://www.devze.com 2023-03-19 14:38 出处:网络
When passing a view model (as below) to a view, how can I ensure that the checkboxes I\'m creating (mapped to item \"Product\" in here) get passed back to the controller?

When passing a view model (as below) to a view, how can I ensure that the checkboxes I'm creating (mapped to item "Product" in here) get passed back to the controller?

I've included my view model and "post" product controller below.

Unfortunately, when posted back to the controller, "Products" is null.

namespace MyProject.Models
{
    public class ChartViewModel
    {
        public Chart ChartItem { get; set; }
        public IEnumerable<Product> Products { get; set; }
    }
}

Controller:

    [Authorize]
    [ValidateInput(false)]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(ChartViewModel objChartViewModel)
    {

        if (!TryUpdateModel(objChartViewModel))
        {
            return View(objChartViewModel);
        }
        else
        {

        } return View("Details", objChartViewModel);

    }

How the checkboxes are added to my view, mapped to the "Product" object within my view model:

@{
   foreach (MyProject.Models.Product objProduct in Model.Products)
 {
            @Html.CheckBox("product" + objProduct.Id, Model.ChartItem.ChartProducts.Select(t => t.ProductId).Contains(objProduct.Id));
            @String.Format(开发者_Go百科"{0} {1}", objProduct.Manufacturer.Name, objProduct.Name);<br />
 }
}


You can send your lists (IEnumerable<T>) down to the view but when they don't come back up to the controller. The only properties of your ViewModel that have values are those with exactly matching items in the forms collection. So add a properties to your ViewModel like SelectedProductID.

This sets up a drop down list that sends its selected value back to the controller:

<div class="editor-field"> 
    @Html.DropDownListFor(m => m.SelectedEmployeeID,
        new SelectList(Model.EmployeeList, "EmployeeID", "EmployeeName"), "--Please select an Employee--")
    @Html.ValidationMessageFor(model => model.SelectedEmployeeID)
</div>

Notice: the property being set is SelectedEmployeeID but this comes from the EmployeeList.

In your case the values many be in the collection (only "checked" checkboxes get sent in a post) so you could do:

string value = collection["myProductID"];

if its there its checked.

sorry for the messiness, this was in a bit of a rush. See this for more info:
MVC 3 form post and persisting model data

0

精彩评论

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

关注公众号