views:

165

answers:

2

Is there any way to have a strongly typed UpdateModel(myEntity, MagicStringPrefix) without the magic string?

So I have a view model looking like

public class FooViewModel {
    public Foo Foo { get; set; }
    ...
}

And in my controller I have

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
    var foo = _fooRepo.GetFoo(id);

    try
    {
        UpdateModel(foo, "Foo");
        _fooRepo.Save();

        return RedirectToAction("Index");
    }
    catch (Exception ex)
    {
        return View(new FooViewModel(foo));
    }
}

I would like to do this without having to use magic strings. Something like UpdateModel(foo, Model.Foo) would be fine. However, I prefer to simply have UpdateModel(foo) and have it infer the prefix given Foo is the class name, but I really don't want to have to write my own ModelBinder.

A: 

You should be able to pass in a strongly typed object in your action method provided that you have all the property name match. I don't think you need to write your own model binding to achieve this.

Read this blog to get some idea.

J.W.
This is using the entity itself as the view model. That works fine. The problem is I am using ClientViewModel.Client which requires me to use the prefix.
jcm
+2  A: 

You can define your own update method:

    protected void MyUpdateModel<T>(T model) where T : class
    {
        UpdateModel(model, model.GetType().Name);
    }
LukLed
Looks like this is what I'm going to have to do. Shame it's not in core MVC. This seems like pretty common functionality. Maybe it'll be in MVC2 ...
jcm