Jeff Lauder
Jeff Lauder

Reputation: 1247

How can I correctly test to see if the model I'm passing to my controller is of a particular type?

I have a view with multiple forms on it. These forms have partial views which are added using Html.RenderPartial(). I want to be able to distinguish between the models in a single actionResult thusly:

    [HttpPost]
    public ActionResult LogOn(dynamic Model, string returnUrl)
    {
        if (Model is RegisterModel)
        {
            Register((RegisterModel)Model, returnUrl);
        }
        return View();
    }

Is there any reason why this doesn't work? I have also tried typing Model as an object instead of a dynamic but that didn't help either. Model.GetType() always returns object, and Model is RegisterModel always returns false. What am I missing about MVC3's behavior that I need to understand here? Thank you for your time

Upvotes: 3

Views: 101

Answers (1)

dknaack
dknaack

Reputation: 60516

At first, why dont create different Action Methods for different ModelTypes ? This would result in better performance and better "seperation of concern." But if you want to do this the way you describe, try this...

Maybe this sounds strange but

It is statically-typed as a dynamic type.

You can create a Custom Model Binder that tryes to bind your POST or GET informations to the type that you want.

public class MyCustomModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        object result;
        HttpRequestBase request = controllerContext.HttpContext.Request;

        // custom logic sample
        if (request.Params["ParamName"].ToString() == "xyz")
        {
            result = new RegisterModel();
            result.Propertie1 = request.Params["Propertie1"];
        }
        else
        {
            // create another model
        }

        return result;
    }
}

Then you can do this.

[HttpPost]
public ActionResult LogOn([ModelBinder(typeof(MyCustomModelBinder))] object Model, string returnUrl)
{
    if (Model is RegisterModel)
    {
        Register((RegisterModel)Model, returnUrl);
    }
    return View();
}

Scott Hanselman wrote a nice Blog Post about the dynamic keyword: C# 4 and the dynamic keyword

More informations about IModelBinder: ASP.NET MVC Custom Model Binding

hope this helps

Upvotes: 2

Related Questions