0

有人能告诉我在使用局部视图时如何让 MVC 绑定到视图模型中的视图模型吗?

 public class HomeController : Controller
    {
        //
        // GET: /Home/

        [HttpGet]
        public ActionResult Index()
        {
            AVm a = new AVm();
            BVm b = new BVm();
            a.BVm = b;

            return View(a);
        }

        [HttpPost]
        public ActionResult Index(AVm vm)
        {
            string name = vm.BVm.Name; // will crash BVm == null


            return View(vm);
        }
    }

// 索引视图

@model MvcApplication4.Models.AVm

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm("Index","Home",FormMethod.Post))
{
    <text>Id:</text> @Html.TextBoxFor(x => x.Id)
    @Html.Partial("SharedView", Model.BVm)

    <input type="submit" value="submit" />
}

// 共享视图

@model MvcApplication4.Models.BVm

<text>Name:</text> @Html.TextBoxFor(x => x.Name)



 Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 26:         public ActionResult Index(AVm vm)
Line 27:         {
Line 28:             string name = vm.BVm.Name; // will crash BVm == null
Line 29: 
Line 30: 
4

1 回答 1

1

问题在于,在您的部分模型中,模型BVm不知道它是 viewmodel 上的属性AVm。所以当你做类似的事情时,@Html.TextBoxFor(x => x.Name)它只会产生类似的东西

<input type="text" name="Name" id="Name" value="" />

当你真正需要的是

<input type="text" name="BVm.Name" id="Name" value="" />

您可以像这里建议的那样自己生成输入,也可以尝试以下操作:

public ActionResult Index(AVm vm, BVm bvm)

假设没有冲突的属性名称。

于 2012-12-02T06:18:07.380 回答