Asp.net MVC2 IModelBinder tries to drive me crazy (and succeeds)

Say I have

class FooClass { }

class BarClass
{
    public FooClass Foo;
}

This BarClass class is the model I pass to ViewPage.

I also pass (via ViewData) IEnumerable<SelectListItem>with all the Foo in it, and the one that matches bar.Foois selected (marked at runtime).

Then i call Html.DropDownList("Foo", foos);

The dropdown will display well, but it does not select the correct item, because the html control has a property name, and it randomly works with ViewData.Eval()which is executed internally. This seems to be accepted behavior (there were a lot of answers about this on SO), so I don’t argue about this and do not change the call to the extension:

Html.DropDownList("DDL_Foo", foos);

The correct value is selected and I am happy. Therefore, I submit the form back.

, Foo NULL. FooModelBinder, IModelBinder, DDL_Foo FooClass.

FooModelBinder.BindModel , bar.Foo null. Foo, FooModelBinder , , bar.Foo , .

, ? , . , , . , .

!

[EDIT] , , .

, , . , , , , , . - , , .

revelant ( ):

CONTROLLER

    [HttpGet]
    public ActionResult Index()
    {
        var dp = new DummyProvider();
        var bar = dp.GetBar();
        var foos = new List<SelectListItem>();

        dp.GetAllFoos().ForEach(
            f => foos.Add(new SelectListItem {Text = f.Name, Value = f.Id.ToString(), Selected = f.Id == bar.Foo.Id }));

        ViewData["foos"] = foos;

        return View(bar);
    }

    [HttpPost]
    public ActionResult Index(BarClass bar)
    {
        var dp = new DummyProvider();
        var foos = new List<SelectListItem>();

        dp.GetAllFoos().ForEach(
            f => foos.Add(new SelectListItem { Text = f.Name, Value = f.Id.ToString(), Selected = f.Id == bar.Foo.Id }));

        ViewData["foos"] = foos;
        ViewData["selectedItem"] = bar.Foo.Name;

        return View(bar);
    }

VIEW

<%
    var foos = ViewData["foos"] as List<SelectListItem>;

    using(Html.BeginForm())
    {
        %>
        <p>
            <h3>Enter Another Value</h3>
            <%= Html.TextBox("AnotherValue", Model.AnotherValue) %>
        </p>
        <p>
            <h3>Enter Yet Another Value</h3>
            <%= Html.TextBox("YetAnotherValue", Model.YetAnotherValue) %>
        </p>

        <p>
            <h3>Choose a foo</h3>
            <%= Html.DropDownList("DDL_Foo", foos)%>
        </p>
        <button type="submit">Send back !</button>
        <%
    } 
%>

MODEL

public class BarClass
{
    public FooClass Foo { get; set; }
    public string AnotherValue { get; set; }
    public string YetAnotherValue { get; set; }
}

public class FooClass
{
    public Guid Id { get; set; }
    public string Name { get; set; }

}

public class FooClassCollection : List<FooClass> { }

public class FooModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var foo = new FooClass();

        var guid = Guid.Empty;
        if (Guid.TryParse(controllerContext.HttpContext.Request.Form["DDL_Foo"], out guid))
        {
            foo.Id = guid;    
        }


        return foo;
    }
}

public class DummyProvider
{
    public FooClassCollection GetAllFoos()
    {
        return new FooClassCollection
                       {
                           new FooClass {Name = "Item 1", Id = new Guid("4a402abd-ab85-4065-94d6-d9fcc0f9b69e")},
                           new FooClass {Name = "Item 2", Id = new Guid("cf20bfd6-0918-4ffc-a6ec-c4cc4ed30e7f")},
                           new FooClass {Name = "Item 3", Id = new Guid("ad81b882-b93e-42b9-a42c-78376dd8f59d")},
                           new FooClass {Name = "Item 4", Id = new Guid("1511c15d-9ae4-4b18-9e10-e02588c21b27")},
                           new FooClass {Name = "Item 5", Id = new Guid("855e4a2f-fc5b-4117-a888-1dc3ebb990fc")},
                       };
    }

    public BarClass GetBar()
    {
        return new BarClass
                   {
                       AnotherValue = "Nice value",
                       YetAnotherValue = "This one is awesome",
                       Foo = new FooClass {Name = "Item 3", Id = new Guid("ad81b882-b93e-42b9-a42c-78376dd8f59d")}
                   };
    }
}

global.asax

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);

        ModelBinders.Binders.Add(typeof(FooClass), new FooModelBinder());
    }

[] codeplex, , , , ( ).

+3
2

, BarClassModelBinder, . :

public class BarModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var bar = new BarClass();

        // In real code, check for nulls, etc.

        bar.AnotherValue = controllerContext.HttpContext.Request.Form["AnotherValue"];
        bar.YetAnotherValue = controllerContext.HttpContext.Request.Form["YetAnotherValue"];

        var guid = Guid.Empty;
        if (Guid.TryParse(controllerContext.HttpContext.Request.Form["DDL_Foo"], out guid))
        {
            bar.Foo = new FooClass {Id = guid};
        }


        return bar;
    }
}

, , FormCollection , - . , , , "" ModelBinder, , - , . , , , . , .

- DropDownListFor.

+1

, . . FooClass, Guid FooId. . :

<%: Html.DropDownListFor(m => m.FooId, foos) %>

FooId.

BarClass - , (obv):

public class BarViewModel
{
    public Guid FooId { get; set; }
    public string AnotherValue { get; set; }
    public string YetAnotherValue { get; set; }
}
0

Source: https://habr.com/ru/post/1757390/


All Articles