在MVC3剃须刀中下拉列表 [英] Drop Down List in MVC3 razor

查看:77
本文介绍了在MVC3剃须刀中下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的型号:



  public   TeamRosterModel 
{
public SelectList ManageList {获得; set ; }
public string 命令{ get ; set ; }
}
public class 员工
{
public string FromEmpID { get ; set ; }
public string EmployeeName { get ; set ; }
}







这是我的看法:

 @ Html.DropDownList(  Employee new  SelectList(Model.ManageList,  Value  Text,Model.ManageList.SelectedValue))





这是我的控制器来设置下拉列表:



列表< ;员工> objEmployee =  new  List< Employee>(); 
for int i = 0 ; i < dsManageFor.Rows.Count; i ++)
{
string d1 = dsManageFor.Rows [i] [ 0 ]。ToString();
string d2 = dsManageFor.Rows [i] [ 1 ]。ToString();
objEmployee.Add( new Employee {FromEmpID = d1,EmployeeName = d2});
}
sqlConn.Close();
objTeamModel.ManageList = new SelectList(objEmployee, FromEmpID EmployeeName 0 );





这是我的控制器代码,用于检索所选值:

< pre lang =cs> string value = objTeamModel.ManageList.SelectedValue;







我可以设置值,但无法从下拉列表中检索所选值...请帮助

解决方案

你应该使用DropDownListFor,这将允许你分配集合和一个变量来存储选定的值。



否则你必须将它从请求中删除。您可以创建一个变量并自动填充它,但最好让框架提前知道您想要的内容。尽管如此,我倾向于一直使用AJAX,所以我最终创建了一个AJAX帖子,它确切地定义了回发的变量,并将它们放在被调用的方法上。


This is my Model:

public class TeamRosterModel
    {
        public SelectList ManageList { get; set; }
        public string Command { get; set; }
    }
    public class Employee
    {
        public string FromEmpID { get; set; }
        public string EmployeeName { get; set; }
    }




This is my view:

@Html.DropDownList("Employee", new SelectList(Model.ManageList, "Value", "Text", Model.ManageList.SelectedValue))



This is my controller to set the drop down list:

List<Employee> objEmployee = new List<Employee>();
            for (int i = 0; i < dsManageFor.Rows.Count; i++)
            {
                string d1 = dsManageFor.Rows[i][0].ToString();
                string d2 = dsManageFor.Rows[i][1].ToString();
                objEmployee.Add(new Employee { FromEmpID = d1, EmployeeName = d2 });
            }
            sqlConn.Close();
            objTeamModel.ManageList = new SelectList(objEmployee, "FromEmpID", "EmployeeName", 0);



This is my controller code to retrieve selected value:

string value = objTeamModel.ManageList.SelectedValue;




I am able to set the values but not able to retrieve the selected value from the drop down... Please help

解决方案

You should use DropDownListFor, that will let you assign the collection AND a variable to store the selected value.

Otherwise you have to pull it out of the Request. You might be able to create a variable and have it auto populate, but you're better off letting the framework know ahead of time what you want. For all that, I tend to use AJAX all the time, so I end up creating an AJAX post that defines exactly what variables are posted back, and put them on the method being called.


这篇关于在MVC3剃须刀中下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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