【问题标题】:Models in viewmodel gave me null error while they are'nt nullviewmodel 中的模型在它们不是 null 时给了我 null 错误
【发布时间】:2015-12-28 07:39:15
【问题描述】:

我正在使用Razor Engine 开发一个Asp.net MVC 5 webApplication。我有一个 layout 显示来自此模型的一些数据: (Footers , FooterMenus , SocialNetworks) 来自 db ,我有一个名为 register.cshtml 的视图,它显示了一个要添加 user 的表单页面。我想将 layout 添加到 register.cshtml 但我不知道如何为此编写 ViewModel。我在下面写了这些代码,但Footers , FooterMenu , SocialNetworks 显示了任何内容,因为RegisterVM 中的这段代码:

 public RegisterVM()
{
    //Initialize these properties to empty list.
    this.Footers = new List<Footer>();
    this.FooterMenus = new List<FooterMenu>();
    this.SocialNetworks = new List<SocialNetwork>();
    this.Users = new List<User>();
}

如果我删除此代码,它会给我一个编译器错误并显示models are null。我该怎么解决这些?! 我为这个错误工作了 3 天:(

注册VM.cs

public class RegisterVM
{
    public int UserID { get; set; }
    public string UserEmail { get; set; }
    public string UserFirstName { get; set; }
    public string UserLastName { get; set; }
    public string UserPassWord { get; set; }
    public string UserCellPhone { get; set; }
    public string UserTell { get; set; }
    public string UserImage { get; set; }
    public string UserAddress { get; set; }
    public Nullable<byte> UserStatus { get; set; }
    public Nullable<System.DateTime> UserBirthDate { get; set; }
    public string UserGender { get; set; }

    public List<SocialNetwork> SocialNetworks { get; set; }
    public List<Footer> Footers { get; set; }
    public List<FooterMenu> FooterMenus { get; set; }
    public List<User> Users { get; set; }

    public RegisterVM()
    {
        //Initialize these properties to empty list.
        this.Footers = new List<Footer>();
        this.FooterMenus = new List<FooterMenu>();
        this.SocialNetworks = new List<SocialNetwork>();
        this.Users = new List<User>();
    }
}

控制器:

[HttpGet]
    public ActionResult Register()
    {
        RegisterVM vm = new RegisterVM();
        vm.UserAddress = "";
        vm.UserBirthDate = DateTime.Now;
        vm.UserCellPhone = "";
        vm.UserEmail = "";
        vm.UserFirstName = "";
        vm.UserGender = "";
        vm.UserID = 1;
        vm.UserImage = "";
        vm.UserLastName = "";
        vm.UserPassWord = "";
        vm.UserStatus = 1;
        vm.UserTell = "";
        return View(vm);
    }
    [HttpPost]
    public ActionResult Register(User user)
    {
        UserRepositories bluser = new UserRepositories();
        if(ModelState.IsValid)
        {
            if(bluser.Add(user))
            {
                //Succsess
            }
            else
            {
                //un Succsess
            }
        }
        else
        {
            //error 
        }
        return View();
    }

RegisterLayout.cshtml

@model NP1.ViewModels.RegisterVM
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>

@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@RenderSection("styles", false)


 </head>
  <body style="width: 100% !important; padding: 0px; overflow-x: hidden;">
//menu is here //
<div>
    @RenderBody()

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", false)
  </div>

 <div>
    <footer class="footer text-center FooterFont hidden-xs" style="bottom: 0;overflow:hidden; text-align: center; color: GrayText; clear: both; margin-bottom: -30px; background-color: #191919 !important; padding-top: 20px;">
        <div class=" text-center" style="background-color:#191919 !important; padding-bottom:20px;width:100%;text-align:center;">

            <ul style="text-align: center; background-color: #191919; list-style-type: none; display: inline-block; vertical-align: top;" class="list-group col-lg-4 col-md-4 col-xs-12 col-sm-4">
                <li class="list-group-item">
                    @foreach (var item in Model.Footers)
                    {
                        <ul style="text-align: center; list-style-type: none; background-color: #191919;">
                            <li class="list-group-item">
                                <a class="aFooter" href="@item.FooterLink">
                                    <span>@item.FooterName</span>
                                </a>
                            </li>
                        </ul>
                    }
                </li>
            </ul>

            <ul style="border-right: 1px graytext solid; border-left: 1px graytext solid; text-align: center; list-style-type: none; display: inline-block; vertical-align: top;background-color:#191919;" class="list-group col-lg-4 col-md-4 col-xs-12 col-sm-4">


                <li class="list-group-item">
                    @foreach (var item in Model.FooterMenus)
                    {
                        <ul style="text-align:center;list-style-type:none;">
                            <li class="list-group-item">
                                <a class="aFooter" href="@item.FooterMenuLink">
                                    <span>@item.FooterMenuName</span>
                                </a>
                            </li>
                        </ul>
                    }
                </li>

            </ul>

            <ul style="text-align: center; list-style-type: none; display: inline-block; vertical-align: top;" class="list-group col-lg-4 col-md-4 col-xs-12 col-sm-4">

                <li class="list-group-item">
                    @foreach (var item in Model.SocialNetworks)
                    {
                        <ul style="text-align:center;list-style-type:none;padding-top:15px;">
                            <li>
                                <a class="aFooter" href="@item.SocialLink">
                                    <img class="img-responsive center-block socialIcon" src="@Url.Content(item.SocialIcon.ToString())" />
                                </a>
                            </li>
                        </ul>
                    }
                </li>
            </ul>


        </div>
    </footer>


    <footer class="footer text-center FooterFont visible-xs" style="bottom: 0;overflow:hidden; text-align: center; color: GrayText; clear: both; margin-bottom: -30px; background-color: #191919 !important; padding-top: 20px;">
        <div class=" text-center" style="background-color:#191919 !important; padding-bottom:20px;width:100%;text-align:center;">

            <ul style="text-align: center; list-style-type: none; display: inline-block; vertical-align: top;" class="list-group col-lg-4 col-md-4 col-xs-6 col-sm-4">
                <li class="list-group-item">
                    @foreach (var item in Model.Footers)
                    {
                        <ul style="text-align:center;list-style-type:none;">
                            <li class="list-group-item">
                                <a class="aFooter" href="@item.FooterLink">
                                    <span>@item.FooterName</span>
                                </a>
                            </li>
                        </ul>
                    }
                </li>
            </ul>



            <ul style=" text-align: center; list-style-type: none; display: inline-block; vertical-align: top;" class="list-group col-lg-4 col-md-4 col-xs-6 col-sm-4">


                <li class="list-group-item">
                    @foreach (var item in Model.FooterMenus)
                    {
                        <ul style="text-align:center;list-style-type:none;">
                            <li class="list-group-item">
                                <a class="aFooter" href="@item.FooterMenuLink">
                                    <span>@item.FooterMenuName</span>
                                </a>
                            </li>
                        </ul>
                    }
                </li>

            </ul>



            <ul style="text-align: center; list-style-type: none;  vertical-align: top;">

                <li>
                    @foreach (var item in Model.SocialNetworks)
                    {
                        <ul class="list-inline" style="text-align:center;list-style-type:none;">
                            <li class="col-xs-3">
                                <a style="padding:3px;" class="aFooter" href="@item.SocialLink">
                                    <img class="img-responsive center-block socialIcon" src="@Url.Content(item.SocialIcon.ToString())" />
                                </a>
                            </li>
                        </ul>
                    }
                </li>
            </ul>


        </div>
    </footer>

</div>


Register.cshtml

@model NP1.ViewModels.RegisterVM

 @{
ViewBag.Title = "register";
Layout = "~/Views/Shared/_RegisterLayout.cshtml";
 }

  @using (Html.BeginForm()) 
  {
 @Html.AntiForgeryToken()

<div class="form-horizontal">

    @Html.ValidationSummary(true)

    <div class="form-group">
        @Html.LabelFor(model => model.UserEmail, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserEmail)
            @Html.ValidationMessageFor(model => model.UserEmail)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserFirstName, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserFirstName)
            @Html.ValidationMessageFor(model => model.UserFirstName)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserLastName, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserLastName)
            @Html.ValidationMessageFor(model => model.UserLastName)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserPassWord, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserPassWord)
            @Html.ValidationMessageFor(model => model.UserPassWord)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserCellPhone, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserCellPhone)
            @Html.ValidationMessageFor(model => model.UserCellPhone)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserTell, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserTell)
            @Html.ValidationMessageFor(model => model.UserTell)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserImage, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserImage)
            @Html.ValidationMessageFor(model => model.UserImage)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserAddress, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserAddress)
            @Html.ValidationMessageFor(model => model.UserAddress)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserBirthDate, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserBirthDate)
            @Html.ValidationMessageFor(model => model.UserBirthDate)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserGender, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserGender)
            @Html.ValidationMessageFor(model => model.UserGender)
        </div>
    </div>

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

 <div>
   @Html.ActionLink("Back to List", "Index")
</div>

【问题讨论】:

  • 布局的模型数据类型是什么?
  • 它是RegisterVM@user1672994
  • 布局是否详细说明了页脚、页脚链接和社交网络的各种局部视图,并且每个局部视图都绑定到特定模型(FooterFooterLinksSocalNetworks)?
  • 不,我没有使用局部视图,我只是在 ul 列表中使用 foreach 显示它们,并且我为所有这些视图模型(RegisterVm)@user1672994

标签: asp.net-mvc razor model viewmodel asp.net-mvc-viewmodel


【解决方案1】:

如果您使用的是 C#6 或更高版本,则可以使用默认属性

//default properties in C#6    
public class RegisterVM
{

public int UserID { get; set; } =1;
public string UserEmail { get; set; } ="";
public string UserFirstName { get; set; } ="";
public string UserLastName { get; set; } ="";
public string UserPassWord { get; set; } ="";
public string UserCellPhone { get; set; } ="";
public string UserTell { get; set; } ="";
public string UserImage { get; set; } ="";
public string UserAddress { get; set; } ="";
public Nullable<byte> UserStatus { get; set; }
public Nullable<System.DateTime> UserBirthDate { get; set; } = DateTime.Now;
public string UserGender { get; set; } ="";


public List<SocialNetwork> SocialNetworks { get; set; }
public List<Footer> Footers { get; set; }
public List<FooterMenu> FooterMenus { get; set; }
public List<User> Users { get; set; }

    public RegisterVM()
    {

        this.Footers = new List<Footer>();
        this.FooterMenus = new List<FooterMenu>();
        this.SocialNetworks = new List<SocialNetwork>();
        this.Users = new List<User>();
    }
}

但主要问题是您没有将视图模型映射到数据库模型。

您还将在帖子中收到您的数据库模型,而不是 viewwmodel。

控制器:

[HttpGet]
public ActionResult Register()
{
    RegisterVM vm = new RegisterVM();
    return View(vm);
}
[HttpPost]
public ActionResult Register(RegisterVM vm)
{


    UserRepositories bluser = new UserRepositories();

    if(ModelState.IsValid)
    {
        User user = new User();
        user.Id=vm.UserID;
        user.FirstName=vm.UserFirstName;            
        user.UserLastName=vm.UserLastName;   
        //etc

        if(bluser.Add(user))
        {
            //Succsess
        }
        else
        {
            //un Succsess
        }
    }
    else
    {
        //error 
    }
    return View();
}

【讨论】:

  • 谢谢亲爱的,但还是一样,数据没有显示。
  • 发表你的观点/cshmtl
  • 您的邮政编码 public ActionResult Register(User user) 需要读取 public ActionResult Register(RegisterVM vm)
  • 我之前添加了这个,但结果没有显示任何变化:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-01
  • 1970-01-01
  • 2019-04-27
相关资源
最近更新 更多