开发者

Creating a generic edit view with ASP.NET, MVC, and Entity Framework

In my database, I have 40 tables that contain only an ID number and a name. My database is accessed using Entity Fram开发者_StackOverflow社区ework. While I have no trouble editing them each by generating a strongly-typed view and postback methods for each object, I would like to create a more generic method and view for viewing and editing these objects.

I am currently using the following code to access each object. In this case, it is for an object of 'AddressType':

public ActionMethod EditAddressType(int ID)
{
    var result = database.AddressType.Single(a => a.ID == ID);
    View(result);
}

[HttpPost]
public ActionMethod EditAddressType(int ID, FormCollection formValues)
{
    var result = database.AddressType.Single(a => a.ID == ID);
    UpdateModel(result);
    database.SaveChanges();
    return View("SaveSuccess");
}

The view 'EditAddressType' is strongly typed and works fine, but there's a lot of repeated code (one instance of this for each object). I've been told that I need to use reflection, but I'm at a loss for how to implement this. My understanding is that I need to retrieve the object type so I can replace the hardcoded reference to the object, but I'm not sure how to get this information from the postback.

I've had success binding the information to ViewData in the controller and passing that to a ViewPage view that knows to look for this ViewData, but I don't know how to postback the changes to a controller.

Thanks for any help you can give me!


If you are going to edit the object you don't need to refetch it from the database in your POST action. The first thing would of course be to abstract my data access code from the controller:

public class AddressesController: Controller
{
    private readonly IAddressesRepository _repository;
    public AddressesController(IAddressesRepository repository)
    {
        _repository = repository;
    }

    public ActionMethod Edit(int id)
    {
        var result = _repository.GetAddress(id);
        return View(result);
    }

    [HttpPut]
    public ActionMethod Update(AddressViewModel address)
    {
        _repository.Save(address);
        return View("SaveSuccess");
    }
}

You will notice that I have renamed some of the actions and accept verbs to make this controller a bit more RESTFul.

The associated view might look like this:

<% using (Html.BeginForm<AddressesController>(c => c.Update(null))) { %>
    <%: Html.HttpMethodOverride(HttpVerbs.Put) %>
    <%: Html.HiddenFor(model => model.Id) %>
    <%: Html.TextBoxFor(model => model.Name) %>
    <input type="submit" value="Save" />
<% } %>

As far as the implementation of this IAddressesRepository interface is concerned, that's totally up to you: Entity Framework, NHibernate, XML File, Remote Web Service call, ..., that's an implementation detail that has nothing to do with ASP.NET MVC.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜