【问题标题】:drop down list in mvc 3mvc 3中的下拉列表
【发布时间】:2012-01-18 13:25:08
【问题描述】:

嘿朋友们,我在我的 mvc 3 项目中使用下拉列表。在这里,用户选择其中一个选项并保存。当他/她重新访问页面时,我必须将最初保存的值设为选定值。实际上,我正在根据需要使用自定义 html 助手来执行此操作。但我遇到了问题。我这样做是:

else if (question_type == 7)
        {
            EAI.DAL.EaiEntities entities = new DAL.EaiEntities();
            QuestionnaireRepository repository = new QuestionnaireRepository(entities);
            SelectList typesList = repository.PopDdlList(qid);                 


            output.Append(helper.Label(questiontext));
            if (answer == "")
            {
                output.Append(helper.DropDownList("ddl" + question_id, typesList, "-- select type----));

            }
            else
            {
                output.Append(helper.DropDownList("ddl" + question_id, typesList, answer));

            }


            return helper.Raw(output.ToString());
        }

实际上上面的代码渲染了从数据库中选择的值,但它实际上替换了 "--select type ---" 。因此,如果我访问同一页面并保存该页面,则保存一次后,我可以在 Formcollection 中获得空值。

所以,请提出适当的方法

【问题讨论】:

    标签: asp.net-mvc-3


    【解决方案1】:

    我通常在我的模型中添加一些属性:

    int SelectedCategory { get; set; }
    
    IEnumerable<SelectListItem> Categories { get; private set; }
    

    然后在我的模型构造函数中加载数据:

    ProductService productService = new ProductService();
    
    this.Categories =
        productService.GetCategories()
            .Select(c => new SelectListItem() { Text = c.Name, Id = c.Id.ToString() });
    
    this.Categories.InsertAt(0, new SelectListItem() { Text = "--- Please Select ---", value = "" });
    

    然后在我的 Razor 标记中执行以下操作:

    @Html.DropDownListFor(m => m.SelectedCategory, Model.Categories)
    

    这应该以标准 MVC 方式自动连接。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多