我有下拉列表,我已从数据库中填写。现在我需要在Controller中获取所选值进行一些操作。但没有得到这个想法。
模型/ UserManageClass.cs
public class UserManageClass
{
// Set Stored Procedure Results to Array
public sp_GetAllDeveloperType_Result dv { get; set; }
public IEnumerable<sp_GetAllDeveloperType_Result> dvi { get; set; }
}
控制器/ ResourceController.cs
public static db_RIROEntities db_RIRO = new db_RIROEntities();
public static UserManageClass model = new UserManageClass();
public ActionResult NewUser()
{
model.dv = db_RIRO.sp_GetAllDeveloperType().FirstOrDefault();
model.dvi = db_RIRO.sp_GetAllDeveloperType();
}
[HttpPost]
// Insert User
public void AddUser(ResourceViewModel resourceInfo)
{
}
视图
using (@Html.BeginForm("AddUser", "Resource", FormMethod.Post))
{
@model OnlineRIRO.Models.UserManageClass
@* Display DropDownList for Developer Type *@
@Html.DropDownListFor(x => x.dv.DeveloperTypeID, new SelectList(Model.dvi, "DeveloperTypeID", "Developer_Type"), new { @class = "form-control input-sm" })
<div class="col-md-4">
<div class="form-group col-lg-12">
<label class="lb-sm">Last Name</label>
<input type="text" name="txtLastName" placeholder="Last Name" class="form-control input-sm">
</div>
</div>
<div class="col-md-4">
<div class="form-group col-lg-12">
<label class="lb-sm">First Name</label>
<input type="text" name="txtFirstName" placeholder="First Name" class="form-control input-sm" id="" value="">
</div>
</div>
}
如何将DropDownList中的Selected Value传递给ResourceViewModel
?
ResourceViewModel
public class ResourceViewModel
{
public string FirstName {get; set;}
public string LastName {get; set;}
}
答案 0 :(得分:2)
您的视图模型应该是表示视图所需属性的类。因此,如果要在视图中添加下拉列表,请向viewmodel添加2个属性,一个用于构建选择选项所需的项目列表,另一个用于所选选项值。
public class ResourceViewModel
{
public int DeveloperTypeId { set;get;}
public List<SelectListItem> DeveloperTypes { set;get;}
public string FirstName {get; set;}
public string LastName {get; set;}
}
现在在您的GET操作中,创建此视图模型的对象,初始化DeveloperTypes
集合属性并将对象发送到视图。
public ActionResult NewUser()
{
var vm = new ResourceViewModel();
vm.DeveloperTypes = db_RIRO.sp_GetAllDeveloperType()
.Select(a=> new SelectListItem {
Value = a.DeveloperTypeID.ToString(),
Text= a.Developer_Type })
.ToList();
return View(vm);
}
[HttpPost]
public void AddUser(ResourceViewModel model)
{
//check model.DeveloperTypeId
// to do : Return something
}
假设db_RIRO.sp_GetAllDeveloperType()
返回DeveloperTypeID
属性int
类型和Developer_Type
string
类型的对象集合。
现在在您看来,您可以使用DropDownListFor
帮助
@model ResourceViewModel
@using(Html.BeginForm("AddUser","Resource"))
{
@Html.LabelFor(a=>a.FirstName)
@Html.TextBoxFor(a=>a.FirstName)
@Html.LabelFor(a=>a.LastName)
@Html.TextBoxFor(a=>a.LastName)
@Html.LabelFor(a=>a.DeveloperTypeId)
@Html.DropDownListFor(a=>a.DeveloperTypeId, Model.DeveloperTypes,"Select");
<button type="submit" class="btn">Submit</button>
}