开发者

What is the purpose of passing a data model instance from within [HttpGet] Create to its View?

I notice there are 2 common practices to implement the Create form.

First Approach From within [HttpGet] Create action method, we pass an instance of data model to the Create.cshtml as follows:

public ActionResult Create()
{
    DataModel dm = new DataModel();
    return View(dm);
}

Second Approach From within [HttpGet] Create action method, we don't pass an instance of data model to the Create.cshtml as follows:

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

The [HttpPost] Create(DataModel dm) for both approaches is as follows:

    [HttpPost]
    public ActionResult Create(DataModel dm)
    {
        if (ModelState.IsValid)
        {
        开发者_StackOverflow    db.Movies.Add(dm);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        else
            return View(dm);
    }

The question is: What is the purpose of passing a data model instance from within [HttpGet] Create to its View ?


Passing a data model to the view associated with the 'Create' is useful if you want the application logic to supply the initial values to be displayed on the form (whether because you don't want them hard-coded in the form defined in the view, or because they might differ depending on the context).


Default values for the bound controls, values in the viewmodel to be consumed by the view to generate dropdowns, etc... as mentioned by rsalmeidafl.

At the risk of sounding like a curmudgeon, this is really best practice. You shouldn't be calling the database to generate select lists and things from your views.

Finally, sending a default instance of the model to your view can also let you reuse edit/create views very easily, since you can bind values without fear of NullRef exceptions for your model. (if you strongly type your views)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜