tags:

views:

42

answers:

4

Hi.

I have a small isuse regarding an interface.

Consider this code:

[HttpPost()]
public void Update(IAuctionItem item) {
    RedirectToAction("List");
}

Whenever I call this I get an exception saying I can't create an instance of type which i totally correct. But is there a way of telling what the interface should map to without actually using the concrete type ?

A: 

You could use the concrete (base) type and then test for the interface internally?

[HttpPost()]
public void Update(BaseItem item)
{
    if (item is IActionItem)
        RedirectToAction("List");
    else
        // do something else
}
James
+1  A: 

You can do this, by providing MVC with a custom mapper telling it how to map to the interface types. See this previous question, and this article about Model Binders.

driis
A: 

It looks like the default model binder is trying to construct an instance of "IAuctionItem", as that is the type your action is demanding.

Two solutions are:

A) Change your action to accept a concrete type.
B) Replace the default model binder a custom model binder that returns an instance of a concrete type that implements "IAuctionItem".

Have a google for Smart Model Binder, which is part of MVCContrib (I think). Using the smart model binder allows you to write custom model binders and drop-back to the default binder if your custom binder doesn't handle the sought type.

Hope this helps.

Paul Suart
A: 

this became my solution. Thanks to all of you guys for helping out :)

[HttpPost()]
public void Update([ModelBinder(typeof(AuctionItemModelBinder))]IAuctionItem item) {
    repository.Update(item);

    RedirectToAction("List");
}

and my custom modelbinder.

public class AuctionItemModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext) {

        NameValueCollection form = controllerContext.HttpContext.Request.Form;

        Registry registry = new Registry();
        var item = registry.ResolveTypeFrom<IAuctionItem>();
        item.Description = form["title"];
        item.Price = int.Parse(form["price"]);
        item.Title = form["title"];

        //TODO: Stop hardcoding this
        item.UserId = 1;

        return item;
    }
}
danielovich