简体   繁体   中英

Looking for the best way to provide a ViewModel on “Add new” View and just part of it / different one as its submit POST response

I'm developing a Web Application by using ASP.Net MVC 5. My model is something similar to:

Person
    - int ID
    - string FullName
    - int PersonTypeId

PersonType
    - Id
    - Name
    - Description

I'm working on the "create new Person" page. I have created a ViewModel with the following structure:

public class SampleAddViewModel
{
    public Person person;
    public SelectList personTypes; // Used to populate the DropDown element.
}

My controller's GET method (to simply display the page):

// GET: Add new person
public ActionResult Add()
{
    SampleAddViewModel savm  = new SampleAddViewModel();
    AddPersonViewModel.personTypes = new SelectList(PersonTypesEntity.GetAll(), "Id", "Name");

    return View(savm);
}

In my controller's POST method (to store the created person) I would expect to just receive the Person model, and not the entire ViewModel. But on the View page I think it is only possible to declare an @model razon line, which I think it must be @model SampleAddViewModel ...

Would it be possible to, in the POST Add entry, have something similar to the following:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add([Bind(Include = "ID, Name, PersonTypeId")] Person person)
{
    if (ModelState.IsValid)
    {
        db.Add(person);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    x <- //Should I re-create the ViewModel in here?
    return View(x);
}

Which would be the best way to address the problem? I'm also trying to avoid using ViewBag. Maybe the best way in fact is to re-send the entire ViewModel.

If you have any errors on the server side on the POST method then yes, you'd want to send the ViewModel back to the view.

Since you are only sending a Person instance into the controller action and your View is expecting an instance of SampleAddViewModel , you should create an instance of one of these and pass it to the View; After all, you're going to need to repopulate the personTypes dropdown with data again.

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