为什么@Model 为空?

Why is @Model null?

查看:Registration.cshtml

 @model MyNameSpace.Models.NewPatientRegistrationViewModel
 <div> ... All the HTML </div>

型号:AccountViewModels.cs

namespace MyNameSpace.Models
{

    public class RegistrationViewModel
    {
        [Display(Name = "Date of Birth")]
        public string DOB { get; set; }
        public int DOBYear { get; set; }
        public int DOBMonth { get; set; }
        public int DOBDay { get; set; }

        public NewPatientRegistrationViewModel() { }
    }

}

控制器:AccountControllers.cs

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

在视图中,对@Model 的引用变为空,并抛出空异常错误。还是 MVC 的新手...我确定我遗漏了一些明显的东西。

将控制器操作更改为 return 将视图模型更改为视图

public ActionResult Registration()
{
    var model = new RegistrationViewModel();
    return View(model);
}

如果您需要渲染视图,您可以在视图模型上实例化其他属性,然后将其传回

模型可能为空的原因有很多,

一个。您可能从 get 方法传递 null。批准的答案指出了这一点。

乙。您可能有一个与您在 post 上绑定模型的参数同名的字段。

public ActionResult Add(ContentImage image)
{
    if (ModelState.IsValid)
    {
        UploadImage(Request.Files["Image"]);

        //Some other actions
    }

    return View("Edit", image);
}

在我看来我有:

@Html.TextBox("Image", string.Empty, new { type = "file" })