Wasfa
Wasfa

Reputation: 266

Getting selected value of dropdownlist from httpGet method to httpPost

I have created a drop downlist in httpGet of controller.Now I want that selected value of dropdownlsit in HttpPost method as a string to perform further operation.In my case i created a dropdownlist of roles in get method,i want to delete that selected role in httpPost method.How can i do it??Any help will be appreciated.Here is my code.

   [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);

    }

View:

       @Html.DropDownListFor( m => m.AllRoles,new SelectList (Model.AllRoles,"Text","Value"))

    [HttpPost]
    public ActionResult DeleteRole()
    {
       //get selected value of dropdownlist in a string??
    }

Upvotes: 0

Views: 1553

Answers (1)

Ahmed ilyas
Ahmed ilyas

Reputation: 5822

I would hope your view does not contain controller code! you would have a Model which would be bound to the selected value so when posted back to the controller action, the value you want is already bound.

you need to create a property in the model as a SelectedValue and bind to that with the list of items coming from another property (Model.AllRoles)

example:

Model:

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

public string SelectedRole {get; set;}

View:

@Html.DropDownListFor(m => m.SelectedRole, Model.AllRoles)

When submitted to your controller, the model will have the selected value

Upvotes: 1

Related Questions