如何在mvc中使用ViewData填充的下拉列表中设置所选值 [英] how to set the selected value in the drop down list populated with ViewData in mvc

查看:112
本文介绍了如何在mvc中使用ViewData填充的下拉列表中设置所选值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是MVC的新手,请帮我在使用查看数据填充的下拉列表中设置所选值,

我已经经历了这么多解决方案,但每个解决方案都处理选择单值的问题下拉。我使用foreach循环列出相同的下拉列表。为该foreach循环中的每个下拉列表设置选定的值。

我的代码如下所示...



[在视图中]



I am new to MVC, please help me to set the selected value in drop down list populated using View Data ,
I have gone through so many solutions but every solutions deals with selecting value for single drop down.I have same drop down listed using the foreach loop. Setting selected value for each dropdown in that foreach loop.
my code is shown below...

[In view]

 int i = 0;

foreach (var item in Model.Select((x, j) => new { Data = x, Index = j + 1 }))
{
  @Html.DropDownListFor(model => item.Data.CategoryID,IEnumerable<SelectListItem>)ViewData["categories"], new { @id = "category" + i })
i++;
  }



[在控制器中]


[in controller]

SelectList selectList = new SelectList((IEnumerable<Category>)ConvertCategoryToList(dt1), "CategoryID", "CategoryName");
           ViewData["categories"] = selectList;

推荐答案

我得到了解决方案.....

感谢大家的回复。



@ Html.DropDownListFor(model => item.Data.CategoryID,new SelectList((IEnumerable< mvcworkstatusmanager.models.category>)ViewData [categories ],CategoryID,CategoryName,item.Data.CategoryID), - 选择类别 - ,新{@id =类别+ i})



在视图页面中声明选择列表为我提供了解决方案。

此代码为我提供了与数据库中每个item.data相对应的正确选择类别。
I got the solution.....
Thanks for the response everyone.

@Html.DropDownListFor(model => item.Data.CategoryID, new SelectList((IEnumerable<mvcworkstatusmanager.models.category>)ViewData["categories"], "CategoryID", "CategoryName", item.Data.CategoryID),"-Select Category-", new { @id = "category" + i })

Declaring select list in the view page give me the solution.
This code gives me the right selected category corresponding to each item.data from the database.


SelectList selectList = new SelectList((IEnumerable<category>)ConvertCategoryToList(dt1), "CategoryID", "CategoryName",1);
            ViewData["categories"] = selectList;

</category>



您已正确书写,只需提及您需要选择哪个ID默认。我手动提到1新的CateogryName



你需要动态检查


You have written correctly only need to mention which id you need to select default. Where I have mention manually 1 new "CateogryName"

You need to check it dynamically


这篇关于如何在mvc中使用ViewData填充的下拉列表中设置所选值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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