模型中的对象在回发时未绑定

时间:2014-12-12 14:16:33

标签: asp.net-mvc

我有一个包含此内容的部分视图:

@model RegisterInputModel
@using (Ajax.BeginForm("Register","Account", null, new AjaxOptions
{
    UpdateTargetId = "signup-partial-update",
    HttpMethod = "POST"
}, new { id = "js-form-signup" }))
{  
    @Html.EditorFor(x=>x.Location,"_RenderLocationInputs")
 // some more fields
}

然后我的_RenderLocationInputs模板(在VIews / Shared / EditorTemplates /中)

@model Location
<span class="location-wrapper">
    <input type="text" id="find-location" placeholder="Your Location (city)" value="@Model.ToShortString()" />
    @Html.HiddenFor(x => x.City, new { id = "hidden-location-city" })
    @Html.HiddenFor(x => x.State, new { id = "hidden-location-state" })
    @Html.HiddenFor(x => x.Country, new { id = "hidden-location-country" })
    @Html.HiddenFor(x => x.Id, new { id = "hidden-location-id" })
</span>

生成:

<span class="location-wrapper">
    <input type="text" id="find-location" placeholder="Your Location (city)" value="" autocomplete="off">
    <input id="hidden-location-city" name="Location.City" type="hidden" value="">
    <input id="hidden-location-state" name="Location.State" type="hidden" value="">
    <input id="hidden-location-country" name="Location.Country" type="hidden" value="">
    <input id="hidden-location-id" name="Location.Id" type="hidden" value="">
</span>

我的控制器操作:

[HttpPost]
public ActionResult Register(RegisterInputModel input)
{
   if (!ModelState.IsValid) return PartialView("Widgets/Register/_RegisterInput", input);
}

我的RegisterInputModel:

public class RegisterInputModel : InputModel
{
   public Location Location { get; set; }
   // other fields and ctor
}

检查chrome POST时,我看到值已正确发送。一个例子: Loccation.City:Blabla

虽然他们没有受我的模式约束。这不是应该如何使用EditorFor模板吗?

我不确定您需要什么代码。只要问你是否需要更多

2 个答案:

答案 0 :(得分:0)

问题:当局部视图模型不是位置而另一个包含位置的模型(以及其他一些东西)时,我可以绑定到RegisterInputModel.Location吗?

绑定基本上取决于name的{​​{1}}属性,但它会发布到服务器。因此,您可以在客户端更改它以绑定不同的方式。

另一件事是从input对象的控制器上手动获取值。

此外,您可以将自己的HttpContext编写为here,但我不认为它会对您的情况有所帮助。

答案 1 :(得分:-1)

只需将完整的RegisterInputModel传递给您的部分并更改此代码

@Html.HiddenFor(x => x.City, new { id = "hidden-location-city" })
@Html.HiddenFor(x => x.State, new { id = "hidden-location-state" })
@Html.HiddenFor(x => x.Country, new { id = "hidden-location-country" })
@Html.HiddenFor(x => x.Id, new { id = "hidden-location-id" })

@Html.HiddenFor(x => x.Location.City, new { id = "hidden-location-city" })
@Html.HiddenFor(x => x.Location.State, new { id = "hidden-location-state" })
@Html.HiddenFor(x => x.Location.Country, new { id = "hidden-location-country" })
@Html.HiddenFor(x => x.Location.Id, new { id = "hidden-location-id" })

它应该有用。