简体   繁体   中英

Asp.net ViewModel and Controller MVC inheritance

Being new to MVC, I'm attempting to edit a pre-existing application with the following structure:

    public ActionResult Create()
    {
        return Edit(new Book());
    }

The Edit method uses an EditView ViewModel. I needed to reference an id so I've added an id to the ViewModel, which works great for editing books, but throws an exception when Creating books as of course no id exists for the model at that point.

What I've done is: Copy the properties from the EditView into a CreateView ViewModel, and just have my EditView extend CreateView as:

public class EditView : CreateView
{
    public Guid Id { get; set; }
}

I then replace the reference to the edit method above with a

return Create(new Book());

And code the create method as per the Edit method but without the reference to the id property, which works but looks ugly due to lots of duplicated code - I now have long Edit and Create methods in my controller which are almost identical bar the id property:

private ActionResult Edit(Book book) { ....

        return View("Edit", new EditView
        {
            Id = book.Id,
            (rest of the object initializer code identical to the Create method)

This just doesn't seem like the way to go - could I perchance get some direction by way of example on this please?

What I do to get around this is to have a partial view with the shared create/edit fields. I embed this partial in my create and edit views. The edit view has an extra id field. In your controller you can do the same; factor out the shared code into a new method and call this method from your create and edit actions. Example here

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