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

9
控制器代码如下:
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或EmployeeType.ResearchInstitute
并且当我使用jquery调用该操作方法时,如何传递参数id和EmployeeType
请提供示例代码。谢谢。

告诉我详情操作方法的URL会是什么样子?如何从视图传递枚举值到操作方法? - Thomas
4个回答

16

将其作为字符串发送并转换为枚举类型,怎么样?

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

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

注意:请求参数为字符串类型。


在后续版本中,看起来 ASP.NET 将为您执行字符串解析,因此您可以直接在操作参数中使用枚举。 - jpaugh

2

这也很酷:

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

然后从您的 Razor 视图中:

<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')
        }
    });

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是您所需的枚举值。并且不要忘记使用[HttpPost]修饰您的Details操作方法。


1
如果您在表单中传递枚举值,它将作为整数显示在控制器中。我认为您有两种处理方式:
  • 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

告诉我详情操作方法的URL会是什么样子?如何从视图传递枚举值到操作方法? - Thomas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接