【问题标题】:Razor DDL to ModelRazor DDL 到模型
【发布时间】:2015-06-03 00:50:30
【问题描述】:

我正在尝试使用 MVC 了解下拉列表,这似乎让我失望了。我一直在修改下面显示的代码,但无法正确处理。

What I am trying to achieve is simple - hard coding some drop down options in the controller, have them appear in the Razor rendered html and when an option is selected, that selected value is bound back to the string property in the model .

使用下面的代码,我无法从视图中访问li

我看过其他指南,但我无法让它发挥作用,考虑到我想要实现的目标,绑定模型对我来说是最佳选择,还是 ViewBag 等会更好?

谁能告诉我哪里出错了?

型号

public class ViewModel {
    public string MyOption { get; set; } }

查看

@model ViewModel
@Html.DropDownListFor(m => m.MyOption, li, "--Select--")

控制器

public ActionResult Index()
        {
            List<SelectListItem> li = new List<SelectListItem>();
            li.Add(new SelectListItem { Text = "Option One", Value = "option1" });
            li.Add(new SelectListItem { Text = "Option Two", Value = "option2" });
            return View(li);
        }

【问题讨论】:

    标签: c# asp.net-mvc razor


    【解决方案1】:

    如果要使用,需要通过MyOption查看。一个有效的选择是创建一个视图模型类,其中包含您需要在视图上处理的所有信息

    视图模型

    public class ViewModel
    {
        public IList<SelectListItem> ItemList {get; set;}
        public string MyOption { get; set; }
    }
    

    查看

    @Html.DropDownListFor(m => m.MyOption, Model.ItemList, "--Select--")
    

    控制器

    public ActionResult Index()
    {
        var li = new List<SelectListItem>();
        li.Add(new SelectListItem { Text = "Option One", Value = "option1" });
        li.Add(new SelectListItem { Text = "Option Two", Value = "option2" });
        var viewModel = new ViewModel 
        { 
            ItemList = li, 
            MyOption = [here your code to fill this] 
        }
    
        return View(viewModel);
    }
    

    【讨论】:

    • 将列表添加到 ViewModel 可能是解决方案,Claudio 欢呼,我们会尽快回复您。
    【解决方案2】:

    您需要确保在视图中声明您的模型,以便访问该模型的任何属性或修饰符

    @model Namespacehere.Models.modelclassname
    

    那么你应该可以使用类似的东西

    @Html.DropDownListFor(m => m.MyOption, model, "--Select--")
    

    【讨论】:

    • 这就是我目前所拥有的,是 li 不正常,MyOption 都很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 2011-06-10
    • 2014-04-20
    相关资源
    最近更新 更多