将数据传递到局部视图

时间:2013-02-23 17:06:12

标签: asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 partial-views

我创建了一个视图页面,其中有两个部分视图登录和注册。对于两者,我创建了视图模型和两者的组合模型,如下所示。

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace ProjectHub.ViewModels
{
    public class LoginModel
    {
         public string Username { get; set; }
         public string Password { get; set; }
    }
    public class RegisterModel
    {
         public string FullName { get; set; }
         public string Email { get; set; }
         //Some properties as well
    }
    public class LoginOrRegisterModel
    {
         public LoginModel Loginmodel { get; set; }
         public RegisterModel Registermodel { get; set; }
    }
}

Index.cshtml      @model ProjectHub.ViewModels.LoginOrRegisterModel

 @Html.Partial("_Register", Model.Registermodel) 
 @Html.Partial("_Login",Model.Loginmodel)

_Login.cshtml

  @model ProjectHub.ViewModels.LoginModel

  @using (Html.BeginForm("Login", "account", FormMethod.Post))
  {
    @Html.ValidationSummary(true)
    <div class="label">@Html.Label("Username")</div>
    <div class="field">@Html.TextBoxFor(m => m.Username)</div>

    <div class="label">@Html.Label("Password")</div>
    <div class="field">@Html.PasswordFor(m => m.Password)</div>

    <input class="field" id="submit" type="submit" value="Login" />
}

_Register.cshtml

 @model ProjectHub.ViewModels.RegisterModel

 @using (Html.BeginForm("Register", "account", FormMethod.Post))
 {
    <div class="label">@Html.Label("Name")</div>
    <div class="field">@Html.TextBoxFor(m => m.FullName)</div>

    //Some other labels and fields

    <input class="field" id="submit" type="submit" value="Sign Up" />
    @Html.ValidationSummary()   
}

 public ActionResult Index()
    {
        return View();
    }

现在,当我尝试运行application.I得到错误“对象引用未设置为对象的实例。”在@ Html.Partial(“_ Register”,Model.Registermodel)和@ Html.Partial(“_ Login”,Model.Loginmodel)的Index.cshtml中。 请帮帮我。

1 个答案:

答案 0 :(得分:2)

看起来主视图中的Model属性为null,呈现这些部分。确保在呈现此主视图的控制器操作内部已正确初始化并将LoginOrRegisterModel传递给视图:

public ActionResult SomeAction()
{
    LoginOrRegisterModel model = new LoginOrRegisterModel();
    model.Loginmodel = new LoginModel();
    model.Registermodel = new RegisterModel();
    return View(model);
}