【问题标题】:MVC4 Nested ViewModel Binding does not workMVC4 嵌套 ViewModel 绑定不起作用
【发布时间】:2013-06-27 14:44:00
【问题描述】:

我有一个 outerViewModel,里面有两个 ViewModel, 当我尝试绑定内部模型时,所有属性都为空...

代码如下:

**Models.cs**

public class OuterModel
{
    public FirstInnerModel firstInnerModel;
    public SecondInnerModel secondInnerModel;
}

public class FirstInnerModel
{
    public string Title;
}

public class SecondInnerModel
{
    public string Title;
}

Index.cshtml

            @using (Html.BeginForm("ActivateFirst", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {

               @Html.ValidationSummary(true)

                <fieldset>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.firstInnerModel.Title)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.firstInnerModel.Title)
                        @Html.ValidationMessageFor(model =>          model.firstInnerModel.Title)
                    </div>
                    <p>
                       <input type="submit" value="Create" />
                    </p>
                 </fieldset>
        }

HomeController.cs

    public ActionResult Index()
    {
        ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

        var model = new OuterModel()
        {
            firstInnerModel = new FirstInnerModel(),
            secondInnerModel = new SecondInnerModel()
        };

        return View(model);
    }

    [HttpPost]
    public void ActivateFirst(FirstInnerModel ggg)
    {


    }

ggg.Title 返回 null...

有人吗?帮忙!

【问题讨论】:

  • 如果你将OuterModel 传递给ActivateFirst,你会得到你的数据吗?
  • 嗨! :)。不... firstInnerModel 和 secondInnerModel 都是 null
  • 您可能需要在表单上为OuterModel 设置一个隐藏字段,以便将其传递回控制器。
  • 在这个例子中,如果我将 outerModel 传递给控制器​​没有工作......但在我原来的项目中它做到了:) 谢谢!

标签: asp.net-mvc asp.net-mvc-4 viewmodel


【解决方案1】:

当您提交表单时,它会将 OuterModel 发布到控制器,因此您需要执行以下操作:

   [HttpPost]
    public void ActivateFirst(OuterModel ggg)
    {
        var whatever = ggg.FirstInnerModel.Title;

    }

【讨论】:

    猜你喜欢
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2017-08-12
    相关资源
    最近更新 更多