ASP.NET mvc4 DropDownListFor pass back an object

Davita

Is there any way to tell DropDownListFor to post back an object instead of an Id? I have the following code:

public class Foo
{
    public int SelectedProductId { get; set; }

    public decimal MonthlyIncome { get; set; }

    public IEnumerable<Product> Products { get; set; }
}

@using(Html.BeginForm())
{
    @Html.DropDownListFor(x => x.SelectedProductId, new SelectList(Model.Products, "Id", "Name"))
    <input type="submit" value="Submit"/>
}

and this works fine. But in my model, I want to have SelectedProduct instead of SelectedProductId. Is it possible to tell MVC to pass back an object instance instead of it's id?

Thanks.

ararog

Yes, sure, first you need to make sure SelectedProduct has Id and Name properties, and then you must make Model.Products return a list of SelectedProduct and override few methods on SelectedProduct like below:

    public override bool Equals(object obj)
    {
        var other = obj as ClientLookup;
        if (other == null)
            return false;

        return Id.Equals(other.Id);
    }

    public override int GetHashCode()
    {
        return Id.GetHashCode();
    }

    public override string ToString()
    {
        return Id.ToString();
    }

By overriding these methods, and ToString especially, you are making sure that internally DropDownListFor will match the SelectedProduct in your Model.Products with the current SelectedProduct in Foo.

The last piece is the ModelBinder, with this mechanism you will be able to convert a http parameter into a object to bet set in your target model, for SelectedProduct you must do this:

public class SelectedProductModelBinder : IModelBinder
{

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        SelectedProduct selectedProduct = new SelectedProduct();
        if (value.AttemptedValue != null && ! "".Equals(value.AttemptedValue))
            selectedProduct.Id = (int)value.ConvertTo(typeof(int));
        else
            selectedProduct.Id = null;

        return selectedProduct;
    }
}

Now don't forget to register the ModelBinder during app initialization:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        ModelBinders.Binders.Add(typeof(SelectedProduct), new SelectedProductModelBinder());
    }
}

Hope this helps.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

DropDownListFor ASP MVC4

From Dev

ASP.NET MVC DropDownListFor returns null on post back

From Dev

ASP.NET mvc DropDownListFor pass type to controller

From Dev

updating object using NHibernate in Asp.net MVC4

From Dev

updating object using NHibernate in Asp.net MVC4

From Dev

MVC4 DropDownListFor Object reference not set to an instance of an object

From Dev

ASP.NET MVC | DropDownListFor gives error Object reference not set to an instance of an object

From Dev

Cascading DropDownListFor ASP.NET MVC

From Dev

Dropdownlistfor MVC ASP.Net VB

From Dev

Cascading DropDownListFor ASP.NET MVC

From Dev

ASP.NET MVC 5 DropDownListFor AutoComplete

From Dev

How to populate an dropdownlistfor from database in ASP.NET MVC 4

From Dev

How to pass a complex model back to the controller in asp.net mvc

From Dev

Pass values of checkBox to controller action in asp.net mvc4

From Dev

How to pass model from view to javascript in asp.net MVC4

From Dev

How to Pass the Email Id value after checking Captcha in Asp.Net Mvc4?

From Dev

How do I pass a ViewModel to an Edit Action in ASP.NET MVC4

From Dev

Pass dropdownlist value from View to Controller in Asp.Net MVC4 without using jquery or javascript?

From Dev

Add automatically anonymous properties to routeValues which is object in ASP.NET MVC4 ActionLink

From Dev

Routing ASP.NET MVC4

From Dev

ASP.NET MVC4 ActionFilters

From Dev

JSON in ASP.NET MVC4

From Dev

Routing in Asp.Net MVC4

From Dev

ASP.NET MVC4 routes

From Dev

Routing ASP.NET MVC4

From Dev

ASP.NET MVC Model Binding With ListBoxFor & DropDownListFor Helpers

From Dev

NullReferenceException in use DropDownListFor in ASP.NET MVC 5

From Dev

NullReferenceException in use DropDownListFor in ASP.NET MVC 5

From Dev

ASP.NET MVC @Html.DropdownListFor wrong selected value

Related Related

  1. 1

    DropDownListFor ASP MVC4

  2. 2

    ASP.NET MVC DropDownListFor returns null on post back

  3. 3

    ASP.NET mvc DropDownListFor pass type to controller

  4. 4

    updating object using NHibernate in Asp.net MVC4

  5. 5

    updating object using NHibernate in Asp.net MVC4

  6. 6

    MVC4 DropDownListFor Object reference not set to an instance of an object

  7. 7

    ASP.NET MVC | DropDownListFor gives error Object reference not set to an instance of an object

  8. 8

    Cascading DropDownListFor ASP.NET MVC

  9. 9

    Dropdownlistfor MVC ASP.Net VB

  10. 10

    Cascading DropDownListFor ASP.NET MVC

  11. 11

    ASP.NET MVC 5 DropDownListFor AutoComplete

  12. 12

    How to populate an dropdownlistfor from database in ASP.NET MVC 4

  13. 13

    How to pass a complex model back to the controller in asp.net mvc

  14. 14

    Pass values of checkBox to controller action in asp.net mvc4

  15. 15

    How to pass model from view to javascript in asp.net MVC4

  16. 16

    How to Pass the Email Id value after checking Captcha in Asp.Net Mvc4?

  17. 17

    How do I pass a ViewModel to an Edit Action in ASP.NET MVC4

  18. 18

    Pass dropdownlist value from View to Controller in Asp.Net MVC4 without using jquery or javascript?

  19. 19

    Add automatically anonymous properties to routeValues which is object in ASP.NET MVC4 ActionLink

  20. 20

    Routing ASP.NET MVC4

  21. 21

    ASP.NET MVC4 ActionFilters

  22. 22

    JSON in ASP.NET MVC4

  23. 23

    Routing in Asp.Net MVC4

  24. 24

    ASP.NET MVC4 routes

  25. 25

    Routing ASP.NET MVC4

  26. 26

    ASP.NET MVC Model Binding With ListBoxFor & DropDownListFor Helpers

  27. 27

    NullReferenceException in use DropDownListFor in ASP.NET MVC 5

  28. 28

    NullReferenceException in use DropDownListFor in ASP.NET MVC 5

  29. 29

    ASP.NET MVC @Html.DropdownListFor wrong selected value

HotTag

Archive