Binding the Model variable to an Action Method in ASP.NET MVC3

.net, asp.net-mvc, asp.net-mvc-3, binding, c#

Solution

I usually add the following to my model:

public class MyViewModel
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public bool IsPeriod { get; set; }

    public RouteValueDictionary RouteValues
    {
        get
        {
            var rvd = new RouteValueDictionary();
            rvd["name"] = Name;
            rvd["surname"] = Surname;
            rvd["isPeriod"] = IsPeriod;
            return rvd;
        }
    }
}

Then you can simply use the RouteValues property in your Url.Action() call.

<img src="@Url.Action("DisplayData", "Home", Model.RouteValues)" alt="Image" />

Or if your prefer less (explicit) code, ignore the model changes and simply do this:

<img src="@Url.Action("DisplayData", "Home", new RouteValueDictionary(Model)" alt="Image" />

Problem

I have a controller `HomeController` with the following `action method`: ``` [HttpPost] public ActionResult DisplayData(MyViewModel myViewModel) { // Do something with myViewModel } ``` The `ViewModel`: ``` public class MyViewModel { public string Name { get; set; } public string Surname { get; set; } public bool IsPeriod { get; set; } } ``` And the following `View` ``` @model AppName.ViewModels.MyViewModel @{ Html.RenderPartial("MyPartialView", Model); } <img src="@Url.Action("DisplayData", "Home", new { myViewModel = Model })" alt="Image" /> ``` I use the Url.Action how it is described here but what I get in the DisplayData action method is null. In the source code I got: ``` <img src="/Home/DisplayData?filters=AppName.ViewModels.MyViewModel" alt="Image" /> ``` so it is passing actually the type instead of the values. The `ViewModel` instead is correctly passed to the partial view. What am I doing wrong?

Original source