Why controller need a parameter of model if it's strongly bound to view ?

Viewed 65

I am new to MVC and was using web forms for the last 4 years but recently moved to MVC which I find quite different.

I created a repository named basicoperations.cs which just contains an InsertMethod with a return type of bool. Then a model which contains 2 properties name, password and then a controller which contains a single action result method and is strongly bound to a view.

When I fill the 2 textboxes on the front end then it submits it to the database. Fine. I understand but what I find confusing is this:

 public ActionResult AddStories2(Stories st)
       {

           Stories s2 = new Stories();
           basicoperations bo = new basicoperations();

           if (bo.insertImages(st))
           {
               ViewBag.Message = "Added";
           }
           else
           {
               ViewBag.Message = "Failed";
           }

           return View("AddStories");
       }

If the view is strongly bound to the model then 1. Why do I still need a Stories object as a parameter? 2. Why the object stories s2 contains null since it's bound?

1 Answers

I don't really understand your questions. To clarify it step by step:

  1. This is an action method called from the view at the submit of the form you mentioned. If your view had two fields name and password I guess your model Stories is something like that (I guess you are talking about two forms since your login model is not called Stories but with the information I have I am trying to clarify some things):

    public class Stories
    {
        public string name { get; set; }
        public string password { get; set; }
    }
    
  2. If your post was submitted correctly then the object Stories st should have the input values of the user.

  3. The object Stories s2 is instantiated in your action and values are never given to the object. Something like that:

    s2.name = "something";
    s2.password = "somethingElse"
    

so it is should be clear why it is null. Else you could instantiate the object like that:

Stories s2 = new Stories(){ name = "something", password = "somethingElse"}
  1. Since for the View you return you don't need a model or any values and you only return a view with it's Viewbag values you don't have to use the object Stories as a parameter. If your View "AddStories" is using this model like this

    @model Stories
    

in the beginning then you have to pass a model. However if you aren't actually using any values of the model like you imply then just delete this line from your view.

Related