复杂对象的MVC模型绑定 [英] MVC Model binding of complex objects

查看:94
本文介绍了复杂对象的MVC模型绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在网上和网上阅读并实现了许多答案,但是没有运气.

I've read and implemented many answers here and around the web but had no luck..

我的模型看起来像这样:

My model looks something like this:

public class CampaignModel : BaseModel
{
    .
    .
    public List<TreeItem> Countries { get; set; }
    .
    .
}

我认为:

@foreach (var country in Model.Countries.Select((value,i)=> new {i, value}))
{
<input type="checkbox" name="campaign.Countries[@country.i].Id" value="@country.value.Id" @(country.value.IsSelected ? "checked=\"checked\"" : "") />
}

在行动中,我有:

[HttpPost]
public ActionResult UpdateTargeting(CampaignModel campaign)
{
    return View(campaign);
}

但是'Countries'属性为空.

But the 'Countries' property turns out null.

我做错了什么? 谢谢

推荐答案

首先,我认为您需要在名称属性中使用Model代替campaign,如下所示:

First I think you need to use Model instead of campaign in the name attributes, like below:

name="@Model.Countries[@country.i].Id"

现在,您的foreach循环将生成如下所示的html代码:

And right now your foreach loop will generate the html code like below:

<input type="checkbox" name="1" value="1"/>
<input type="checkbox" name="2" value="2" checked=""checked""/>

使用上面的代码,模型绑定将不起作用,这就是为什么您提交表单时会得到空值的原因.您需要如下所示的内容:

With above code, the model binding will not work, that's why you got null values when you submitted the form. You need something like below:

<input id="Countries_0__IsSelected" name="Countries[0].IsSelected" type="checkbox" value="true"/>
<input name="Countries[0].IsSelected" type="hidden" value="false"/>
<input checked="checked" id="Countries_1__IsSelected" name="Countries[1].IsSelected" type="checkbox" value="true"/>
<input name="Countries[1].IsSelected" type="hidden" value="false"/>

所以我建议您使用Razor语法,如下所示:

So I suggest you to use Razor syntax, like below:

foreach (var country in Model.Countries.Select((value,i)=> new {i, value}))
{
      @Html.CheckBoxFor(m => m.Countries[@country.i].IsSelected )    
}

这篇关于复杂对象的MVC模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆