如何设置MVC3 DROPDOWNLIST选定值 [英] How to set Dropdownlist selected value in mvc3
问题描述
我有一个DropDownList其与TempData.when结合它即将第一次被示出所有values.After选择该值在数据库中保存的特定值correctly.But所选值没有showing.I我给我下面code。
有关检索我已经写在指数动作控制器
的TempData [客户] =(IEnumerable的< SelectListItem>)。ClientService.GetALLClientsName()选择(C =>新建SelectListItem {值= C.CLIENT_ID.ToString()文本= C.CLIENT_NAME});
编辑后检索时,我无法获得所选择的value.I写在这样的剃须刀低于
@if(TempData的[SelectedClientName] = NULL&放大器;!&安培;!TempData的[SelectedClientId] = NULL)
{
的foreach(在lstClients SelectListItem SLI)
{
如果(sli.Value.Equals(TempData的[SelectedClientId]的ToString())。)
{
。sli.Text = TempData的[SelectedClientName]的ToString();
sli.Value = TempData的[SelectedClientId]的ToString()。
sli.Selected =真;
打破; }
} } @ Html.DropDownList(drpClientName,lstClients - 选择 - )
我已经转换的TempData [客户端在lstClients.Please帮助我。
公众的ActionResult指数(){
VAR selectedClientId = 5; //为例(与你的变量修改)
ViewBag.Clients =新的SelectList(ClientService.GetALLClientsName()
CLIENT_ID,CLIENT_NAME,selectedClientId)
}
查看:
@ Html.DropDownList(drpClientName(的SelectList)ViewBag.Clients - 选择 - )
的TempData code>有不同的用法。它的行为就像是
会话
但它仅存下一个请求。重定向和希望传递数据时,这是非常有用。见<一href=\"http://stackoverflow.com/questions/12676924/what-is-the-right-time-for-viewdata-viewbag-session-tempdata\">this链接更好地理解上的差异。
I have a dropdownlist which is binding with TempData.when it is coming first time it is showing all values.After selecting a particular value that value is saving in the database correctly.But the selected value is not showing.I am giving my code below.
For retrieving I have written in index action controller
TempData["Clients"] = (IEnumerable<SelectListItem>)ClientService.GetALLClientsName().Select(C=>new SelectListItem { Value=C.CLIENT_ID.ToString(),Text=C.CLIENT_NAME});
when retrieving after editing I can not get the selected value.I have written in razor like this below
@if (TempData["SelectedClientName"] != null && TempData["SelectedClientId"] != null)
{
foreach (SelectListItem sli in lstClients)
{
if (sli.Value.Equals(TempData["SelectedClientId"].ToString()))
{
sli.Text = TempData["SelectedClientName"].ToString();
sli.Value = TempData["SelectedClientId"].ToString();
sli.Selected = true;
break;
}
}
}
@Html.DropDownList("drpClientName", lstClients, "--Select--")
I have converted TempData["Clients"] in lstClients.Please help me.
public ActionResult Index(){
var selectedClientId = 5; // for example (change it with your variable)
ViewBag.Clients = new SelectList(ClientService.GetALLClientsName(),
"CLIENT_ID", "CLIENT_NAME", selectedClientId)
}
View:
@Html.DropDownList("drpClientName", (SelectList)ViewBag.Clients, "--Select--")
TempData
has different usage. It's behavior is like Session
but it survives only next request. It's useful when redirecting and want to pass data. See this link to better understand the difference.
这篇关于如何设置MVC3 DROPDOWNLIST选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!