Why is @Model null?

View: Registration.cshtml

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

      

Model: 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() { }
    }

}

      

Controller: AccountControllers.cs

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

      

In the view, the @Model reference is null and throws an exception error. Still new to MVC ... I'm sure I'm missing something obvious.

+3


source to share


2 answers


change your controller action to return the view model to the view

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

      



You can instantiate other properties in your viewmodel before passing it in if you need your view to render

+4


source


There are many reasons why a model could be null,

and. You can pass null from the get method. The approved answer points to this.

Q. You may have a field that has the same name as a parameter that binds your model to a message.



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

        //Some other actions
    }

    return View("Edit", image);
}

      

And, in my opinion, I had:

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

      

0


source







All Articles