C# 从httpGet方法到httpPost获取dropdownlist的选定值

C# 从httpGet方法到httpPost获取dropdownlist的选定值,c#,asp.net,html.dropdownlistfor,C#,Asp.net,Html.dropdownlistfor,我已经在controller的httpGet中创建了一个dropdownlist。现在我希望HttpPost方法中dropdownlsit的选定值作为字符串来执行进一步的操作。在我的例子中,我在get方法中创建了一个角色dropdownlist,我想在HttpPost方法中删除该选定的角色。我该如何做?任何帮助都将不胜感激。这是我的代码 [HttpGet] public ActionResult DeleteRole(RoleManager role) {

我已经在controller的httpGet中创建了一个dropdownlist。现在我希望HttpPost方法中dropdownlsit的选定值作为字符串来执行进一步的操作。在我的例子中,我在get方法中创建了一个角色dropdownlist,我想在HttpPost方法中删除该选定的角色。我该如何做?任何帮助都将不胜感激。这是我的代码

   [HttpGet]
    public ActionResult DeleteRole(RoleManager role)
    {

       string[] allRoles = ((CustomRoleProvider)Roles.Provider).GetAllRoles(role);
        var roleModel = new RoleManager
        {
            AllRoles = allRoles.Select(x => new SelectListItem() { Text = x, Value = x })
        };

        return View(roleModel);

    }
视图:


我希望您的视图不包含控制器代码!您将拥有一个绑定到所选值的模型,因此当发回控制器操作时,您想要的值已经绑定

您需要在模型中创建一个属性作为SelectedValue,并使用来自另一个属性(model.AllRoles)的项列表绑定到该属性

例如:

型号:

public IEnumerable<SelectListItem> AllRoles {get; set;}

public string SelectedRole {get; set;}

当提交到控制器时,模型将具有选定的值

它给出了一个错误,即在@Html.DropDownListFor(m=>m.SelectedRole,model.AllRoles)这一行对象引用未设置为引用实例,因为您需要正确编码-我刚才给了您一个需要修改到项目中的示例。
public IEnumerable<SelectListItem> AllRoles {get; set;}

public string SelectedRole {get; set;}
@Html.DropDownListFor(m => m.SelectedRole, Model.AllRoles)