如何坚持传递到局部视图的数据模型? [英] How to persist data models passed to partial views?

查看:85
本文介绍了如何坚持传递到局部视图的数据模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了说明我所面临的问题,我已经把三个简单的数据模型:

To illustrate the problem I face, I have put together three simple data models:

 public class PersonalModel {
     public string FirstName { get; set; }
     public string LastName { get; set; }
 }

 public class AddressModel {
     public string Street { get; set; }
 }

 public class OverallModel {
    public string Id { get; set; }
    public PersonalModel Personal { get; set; }
    public AddressModel Address { get; set; }
 }

下面是我的简单Index.chtml:

Here is my simple Index.chtml:

@model WebAppTest.Models.OverallModel
@using (Html.BeginForm())
{
  @Html.AntiForgeryToken()

  <div class="form-horizontal">
    <h4>OverallModel</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.Id)

    <div>
        @Html.Partial("Personal", Model.Personal)
    </div>
    <div>
        @Html.Partial("Address", Model.Address)
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>
  </div>
}

在单击保存按钮,下面的控制器方法被调用:

When the "Save" button is clicked, the following controller method gets invoked:

[HttpPost]
public ActionResult Index(OverallModel model) {
    return View(model);
}

我的问题是, model.Personal model.Address 值始终显示在为空控制器的方法。

The problem I have is that model.Personal and model.Address values always show up as null in the controller method.

虽然值正确获得通过的部分景色,被点击时提交剃刀发动机不能够把整体目标重新走到一起。

Although the values are correctly getting passed to the partial views, the Razor engine is not able to put the overall object back together when submit is clicked.

应该AP preciate它,如果你能见识一下它是什么,我很想念。问候。

Would appreciate it if you could enlighten me on what is it that I am missing. Regards.

推荐答案

通过 OverallModel 来的谐音,这样的控件将被正确地命名为回发到 OverallModel 。目前,你将有 NAME =名字控制,但他们需要 NAME =Personal.FirstName

Pass the OverallModel to your partials so that the controls will be correctly named for posting back to OverallModel. Currently you would have controls with name="FirstName" but they need to be name="Personal.FirstName"

@Html.Partial("Personal", Model)

和改变谐音,以适应

@model OverallModel
....
@Html.TextBoxFor(m => m.Personal.FirstName)

作为一种替代方法,还可以通过preFIX到部分

As an alternative, you can also pass the prefix to the partial

@Html.Partial("Address", Model.Personal, new ViewDataDictionary { TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "Personal" }})

这篇关于如何坚持传递到局部视图的数据模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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