简体   繁体   中英

Passing strongly typed viewdata to view page in asp.net-mvc

Do I have to manually pass my strongly typed viewdata to the call return View(); ?

ie.

MyViewData vd = new MyViewData();

vd.Blah = "asdf asdfsd";

return View();

It seems if I pass it as a parameter, I have to repeat the view name also?

return View("index", vd);

you can simply pass the model the the View method:

MyViewData vd = new MyViewData();

vd.Blah = "asdf asdfsd";

return View(vd);

Normally you don't have to manually pass it, but your model has to have a constructor without parameters. Otherwise the framework won't know what values you would like it to pass there.

As for passing the view name, just check out all method overloads. If there is one with just the model as a parameter, then you can omit the view name.

You can do this:

public ActionResult Action()
{
    var vd = new MyViewData();

    vd.Blah = "asdf asdfsd";

    ViewData.Model = vd;

    return View();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM