如何将Enum从视图传递到模型ASP.Net MVC

控制器代码看起来像

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 ,该form action method将指向Details操作方法并传递枚举值,如EmployeeType.RecruitmentOffice or EmployeeType.ResearchInstitute

再次当我将通过jquery调用该动作方法时,我怎么能传递for id & EmployeeType参数。

请与示例代码讨论。 谢谢

怎么样发送string并转换为枚举

 public ActionResult Details(int id, string type) { EmployeeType empType= (EmployeeType) Enum.Parse( typeof(EmployeeType), type, true ); } 

或者写自定义模型绑定器。

注意:请求参数是字符串

如果您的枚举定义如下:

 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您需要Enum Value 。 并且不要忘记使用[HttPost]装饰您的Details操作方法。

这也很酷:

 [Flags] public enum PersonRole { User, Student, Instructor }; 

然后从你的剃刀视图:

  

并在您的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') } }); 

如果在表单中传递枚举值,它将在您的控制器中显示为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-模型绑定-数据注解