从视图传递列表控制器,MVC3 [英] Passing list from view to controller, MVC3

查看:136
本文介绍了从视图传递列表控制器,MVC3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的项目创建一个标签系统。我需要传递一个字符串(为前:TEST1,TEST2,TEST3),将被绑定到一个实体作为一个列表。

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.

我使用的EF和我的观点继承的实体,在EF定义。如果没有创建一个视图模型,是有可能做到这一点?

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

推荐答案

老实说查看车型去这里的道路。

Quite honestly view models is the way to go here.

但是,因为你问我会尽量回答。 IIRC EF车型分部类,这意味着你可以属性添加到他们,是这样的:

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();
    }
}

然后 /家庭/索引?值= VAL1,val2中,VAL3 要正确绑定到列表中。

这篇关于从视图传递列表控制器,MVC3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆