在mvc razor的dropdownlist中设置选定的值 [英] set selected value in dropdownlist in mvc razor
本文介绍了在mvc razor的dropdownlist中设置选定的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将我选择的状态设置为此状态下拉列表。我没有任何想法设置这个。请使用以下代码帮助一些人。
Model(ClaimModel):
i wanna set my selected state into this state dropdownlist. i dont have any idea to set this . please help some one with this below code.
Model(ClaimModel ):
public DataSet Bindcarrier()
{
//StudentContext db = new StudentContext();
try
{
con.Open();
DataSet ds = new DataSet();
if (con.State == ConnectionState.Open)
{
SqlCommand cmd = new SqlCommand("usp_ddlb_ref_carrier_login", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@pi_is_active", 1);
cmd.Parameters.AddWithValue("@pi_login_id", DBNull.Value);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
return ds;
}
else
{
return ds;
}
}
finally
{
con.Close();
}
}
查看:
@ Html.DropDownList(state,null,new {@class =drplist})
控制器:
View:
@Html.DropDownList("state", null, new { @class = "drplist" })
Controller:
[HttpGet]
public ActionResult Create(Boolean Name)
{ ClaimModel obj = new ClaimModel();
DataSet ds = obj.Bindstate();
ViewBag.fname = ds.Tables[0];
List<SelectListItem> items = new List<SelectListItem>();
foreach (System.Data.DataRow dr in ViewBag.fname.Rows)
{
items.Add(new SelectListItem { Text = @dr["state_short_name"].ToString(), Value = @dr["state_id"].ToString() });
}
ViewBag.State = items;
}
推荐答案
SelectListItem [ ^ ]具有属性选择...设置为正确的项目,它将是选定的...
SelectListItem[^] has property Selected...set it for the right item and it will be the selected one...
items.Add(new SelectListItem { Text = @dr["state_short_name"].ToString(), Value = @dr["state_id"].ToString(), Selected = (@dr["state_id"] == any_index) });
我使用DropdownListFor()
我使用模型而不是视图包的方法略有不同。模型是Controller调用的单独类。此堆栈溢出中给出了一个示例 c# - MVC ViewModel示例 - 堆栈溢出 [ ^ ]
为了在你的模特中工作,你需要2个属性。
I use DropdownListFor()
Which has a slightly different approach I use a model not a view bag. A model is a separate class called by the Controller. An example is given in this stack overflow c# - MVC ViewModel example - Stack Overflow[^]
For this to work in your model you need 2 properties.
public List<SelectListItem> items {get;set;}
public int MyAssignedToValue {get;set;}
然后在你的视图中
then in your view
@Html.DropdownListFor(a=> a.MyAssignedToValue, Model.items)
这篇关于在mvc razor的dropdownlist中设置选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文