C# 如何将枚举从视图传递到ASP.NETMVC模型
控制器代码如下所示C# 如何将枚举从视图传递到ASP.NETMVC模型,c#,asp.net-mvc,enums,C#,Asp.net Mvc,Enums,控制器代码如下所示 public class EmployeeController : Controller { public enum EmployeeType { RecruitmentOffice, ResearchInstitute } public ActionResult Details(int id, EmployeeType type) { switch (type)
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;
}
}
}
现在我想知道如何生成表单操作方法
,它将指向详细信息
操作方法并传递枚举值,如EmployeeType.RecruptimentOffice或EmployeeType.ResearchInstitute
同样,当我将通过jquery
调用该操作方法时,我如何为id&EmployeeType传递参数
请与示例代码讨论。谢谢如果在表单中传递枚举值,它将在控制器中显示为int。我认为你有两种方法来处理这个问题:
- 将
type
参数设置为int,然后在操作中将其强制转换为枚举
- 制作一个特定的模型绑定器,用于查找名为
type
的输入,并在开始操作之前尝试转换它
一些带有示例代码的链接可能会帮助您:
作为字符串发送并转换为enum怎么样
public ActionResult Details(int id, string type)
{
EmployeeType empType= (EmployeeType) Enum.Parse(
typeof(EmployeeType), type, true );
}
或者编写自定义模型活页夹
注意:如果您的枚举是这样定义的,则请求参数是string:
public enum EmployeeType {
RecruitmentOffice, //value = 0
ResearchInstitute //value = 1
}
var enumVal = 0; @* RecruitmentOffice *@
$.ajax({
url: '@(Url.Action("Details", "Employee"))',
type: 'POST',
dataType: 'json',
data: {
id: employeeId ,
type: enumVal
}
success: function (result) {
@* Handle success *@
}
}
在视图(*.cshtml)中,可以按如下方式传递枚举值:
public enum EmployeeType {
RecruitmentOffice, //value = 0
ResearchInstitute //value = 1
}
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]装饰你的细节动作方法这也很酷:
[Flags]
public enum PersonRole { User, Student, Instructor };
然后从你的观点来看:
<button onclick="onclickDeleteRole('@(PersonRoleEnum.User|PersonRoleEnum.Student)')">
以及控制器的操作:
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')
}
});
只需告诉我详细操作方法的url会是什么样子?如何将枚举的值从视图传递到操作方法?请告诉我操作方法的详细信息的url是什么样子?如何将枚举的值从视图传递到操作方法?在更高版本中,ASP.NET将为您执行字符串解析,因此您可以在操作参数中直接使用枚举。