MVC3 list passing from view to controller

asp.net-mvc c# entity-framework

Question

I'm trying to create a tagging system for my project. I need the pass a string (for ex: "test1, test2, test3") which will be binded to an entity as a list.

I'm using EF and my view inherits an entity, defined in EF. Without creating a view model, is it possible to do that?

1
1
1/30/2011 12:32:07 PM

Accepted Answer

Quite honestly view models is the way to go here.

But because you asked I will try to answer. IIRC EF models are partial classes, meaning that you could add properties to them, like this:

public partial class MyEFModel
{
    public IEnumerable<string> List
    {
        get
        {
            return SomeStringProperty.Split(',');
        }
        set
        {
            SomeStringProperty = string.Join(",", value.ToArray());
        }
    }
}

Another way to achieve this is to write a custom model binder, like this:

public class MyBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (value != null)
        {
            return value.AttemptedValue.Split(',');
        }

        return base.BindModel(controllerContext, bindingContext);
    }
}

public class HomeController : Controller
{
    public ActionResult Index(
        [ModelBinder(typeof(MyBinder))] IEnumerable<string> values
    )
    {
        return View();
    }
}

and then /home/index?values=val1,val2,val3 should bind correctly to the list.

2
1/30/2011 12:46:39 PM

Popular Answer

There are couple of ways to achieve this:

  1. Custom Action Filter
  2. Custom Model Binder

These implementations can be found here:

Is it possible to change the querystring variable in ASP.NET MVC path before it hits the controller?



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow