asp.net-mvc – ASP.NET MVC DropDown编辑器模板

我正在寻找使用MVC创建下拉列表编辑器模板的最佳方法.似乎有各种各样的方法,但我找不到任何最好的方法,每个人都似乎做的不同.我也使用MVC3与剃刀一样,所以一个适用于此的方法是首选.

解决方法

有很多方法和说法,最好的是主观的,可能不会在你的情况下工作,你忘记在你的问题上描述.这是我如何做到的:

模型:

public class Myviewmodel
{
    public string SelectedItem { get; set; }
    public IEnumerable<Item> Items { get; set; }
}

public class Item
{
    public string Value { get; set; }
    public string Text { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new Myviewmodel
        {
            // Todo: Fetch this from a repository
            Items = new[] 
            {
                new Item { Value = "1",Text = "item 1" },new Item { Value = "2",Text = "item 2" },new Item { Value = "3",Text = "item 3" },}
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(Myviewmodel model)
    {
        if (!ModelState.IsValid)
        {
            // redisplay the view to fix validation errors
            return View(model);
        }

        // Todo: The model is valid here => 
        // perform some action using the model.SelectedItem 
        // and redirect to a success page informing the user
        // that everything went fine
        return RedirectToAction("Success");
    }
}

查看(〜/ Views / Home / Index.cshtml):

@model MyApp.Models.Myviewmodel

@{ Html.BeginForm(); }
    @Html.EditorForModel()
    <input type="submit" value="OK" />
@{ Html.EndForm(); }

编辑器模板(〜/ Views / Home / EditorTemplates / Myviewmodel.cshtml):

@model MyApp.Models.Myviewmodel

@Html.DropDownListFor(x => x.SelectedItem,new SelectList(Model.Items,"Value","Text"))

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....