控制器代码看起来像
public class EmployeeController : Controller
{
public enum EmployeeType
{
RecruitmentOffice,
ResearchInstitute
}
public ActionResult Details(int id, EmployeeType type)
{
switch (type)
{
case EmployeeType.RecruitmentOffice:
// load repository
// load domain object
// load view specific to recruitment office
break;
case EmployeeType.ResearchInstitute:
// load repository
// load domain object
// load view specific to recruitment office
break;
}
}
}
现在我想知道如何生成form action method
,它将指向Details
操作方法并传递枚举值,如EmployeeType.RecruitmentOffice or EmployeeType.ResearchInstitute
再次当我通过jquery
调用该操作方法时,我怎样才能传递参数for id & EmployeeType
。
请与示例代码讨论。感谢
答案 0 :(得分:8)
如果发送string
并转换为枚举
public ActionResult Details(int id, string type)
{
EmployeeType empType= (EmployeeType) Enum.Parse(
typeof(EmployeeType), type, true );
}
或者写自定义模型绑定器。
注意: 请求参数是字符串
答案 1 :(得分:1)
如果您的枚举定义如下:
public enum EmployeeType {
RecruitmentOffice, //value = 0
ResearchInstitute //value = 1
}
在您的视图(* .cshtml)中,您可以传递枚举值,如下所示:
var enumVal = 0; @* RecruitmentOffice *@
$.ajax({
url: '@(Url.Action("Details", "Employee"))',
type: 'POST',
dataType: 'json',
data: {
id: employeeId ,
type: enumVal
}
success: function (result) {
@* Handle success *@
}
}
enumVal 是您需要的枚举值。并且不要忘记用 [HttPost] 装饰您的详细信息操作方法。
答案 2 :(得分:1)
这也很酷:
[Flags]
public enum PersonRole { User, Student, Instructor };
然后从你的剃刀视角:
<button onclick="onclickDeleteRole('@(PersonRoleEnum.User|PersonRoleEnum.Student)')">
并在您的javascript中:
function onclickDeleteRole(role) {
var personId = $('#SelectedPersonId').val();
$.ajax({
url: window.getUrl('Person/DeletePersonRole'),
type: 'POST',
dataType: 'json',
data: {
personId: personId,
roles: role
},
success: function (json) {
alert('success!')
},
error: function (jqXHR, status, error) {
alert('error')
}
});
}
和您的控制器操作:
public JsonResult DeletePersonRole(int personId, PersonRoleEnum roles)
{
// do business logic here...
// roles will now have value PersonRoleEnum.User|PersonRoleEnum.Student
// and you can use roles.HasFlag(PersonRoleEnum.User) to check if that flag is set
return Json(new {Result = "OK"});
}
编辑:为了便于阅读,你总是可以在javascript中使用字符串,而MVC会为你解析这些字符串,例如。
$.ajax({
url: window.getUrl('Person/DeletePersonRole'),
type: 'POST',
dataType: 'json',
data: {
personId: 1,
roles: 'Student'
},
success: function (json) {
alert('success!')
},
error: function (jqXHR, status, error) {
alert('error')
}
});
答案 3 :(得分:0)
如果在表单中传递枚举值,它将在您的控制器中显示为int。我认为你有两种方法可以解决这个问题:
type
参数设为int,然后将其转换为动作中的枚举type
的输入,并在进入您的操作之前尝试将其强制转换。一些包含示例代码的链接可以帮助您: http://www.codeproject.com/Articles/605595/ASP-NET-MVC-Custom-Model-Binder http://www.codeproject.com/Articles/551576/ASP-NET-MVC-Model-Binding-and-Data-Annotation