1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.