Pass (Send) DropDownList selected value to Controller using jQuery Ajax in ASP.Net MVC

bigbear
 
on Apr 03, 2019 11:57 PM
Sample_131764.zip
4735 Views

Hello everyone

I have a dropdownlistfor() with a in my view and I have a button type=submit being used by a different control. I added another button and I would like to get my selected value from my dropdownlistfor

so I can use it in my button click.

Here is my view setup

@using (Html.BeginForm())
{
    <div class="panel panel-default">
        <div class="panel-heading">Choose Administrator</div>
        <div class="panel-body">
            @if (TempData["Success"] != null) {}
            @if (TempData["Error"] != null) {}
            @Html.AntiForgeryToken()
            <div class="row">
                <div class="col-md-4">@*This is the value I want *@
                    @Html.DropDownListFor(a => a.UserId,
                     new SelectList(Model.lstAdmins, "UserId", "Name"),
                     new { @class = "form-control" })
                    @Html.ValidationMessageFor(a => a.UserId)
                </div>
            </div>
        </div>
    </div>

    <div class="panel panel-default">
        <div class="panel-body">
        <div class="clearfix"></div>
        <div class="row">
            @for(var i = 0; i < Model.lstUsers.Count(); i++)
            {
                <div class="col-md-4">
                    <div>
                        @Html.CheckBoxFor(u => Model.lstUsers[i].SelectedUsers)
                        <label>
                            @Html.DisplayFor(u => Model.lstUsers[i].Name)
                            @Html.HiddenFor(u => Model.lstUsers[i].UserId)
                            @Html.HiddenFor(u => Model.lstUsers[i].Name)
                        </label>
                    </div>
                </div>
            }
        </div>
        <div class="row">
            <div class="form-group">
                <div class="col-md-offset-0 col-md-12">
                   <input type="submit" value="Assign Role" class="btn btn-success"/>

@*THIS IS THE BUTTON I WANT THE DROPDOWNLISTFOR VALUE FOR *@

<button type="button" onclick="@Url.Action("RemoveAdmin", "SuperAdmin")" 
    value="Remove Role" class="btn btn-danger"></button>

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Apr 04, 2019 03:39 AM

Hi bigbear,

Since you are not using Fom Post method you have to make Ajax call and pass the dropdownlist value to the ActionResult and do rest of code.

Check the below example.

HTML

<html>
<head>
    <title>Index</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <script type="text/javascript">
        $(function () {
            $('#btnRemoveRole').click(function () {
                var userid = $("#ddlAdmins").val();
                if (userid != "") {
                    $.ajax({
                        url: "Home/RemoveRole",
                        data: { id: userid },
                        type: "POST",
                        success: function (response) {
                        },
                        error: function () {
                            alert("Error");
                        }
                    });
                }
            });
        });
    </script>
</head>
<body>
    <%using (Html.BeginForm())
      {%>
    <div class="panel panel-default">
        <div class="panel-heading">
            Choose Administrator</div>
        <div class="panel-body">
            <div class="row">
                <div class="col-md-4">
                    <%:Html.DropDownListFor(a => a.UserId, new SelectList(Model.lstAdmins, "UserId", "Name"), new { @class = "form-control", @id = "ddlAdmins" })%>
                </div>
            </div>
        </div>
    </div>
    <div class="panel panel-default">
        <div class="panel-body">
            <div class="clearfix">
            </div>
            <div class="row">
                <%for (var i = 0; i < Model.lstUsers.Count(); i++)
                  {%>
                <div class="col-md-1">
                    <%:Html.CheckBoxFor(u => Model.lstUsers[i].SelectedUsers) %>
                    <label>
                        <%:Html.DisplayFor(u => Model.lstUsers[i].Name)%>
                        <%:Html.HiddenFor(u => Model.lstUsers[i].UserId)%>
                        <%:Html.HiddenFor(u => Model.lstUsers[i].Name)%>
                    </label>
                </div>
                <%} %>
            </div>
            <br />
            <div class="row">
                <div class="form-group">
                    <div class="col-md-offset-0 col-md-12">
                        <input type="submit" value="Assign Role" class="btn btn-success" />
                        <button id="btnRemoveRole" type="button" class="btn btn-danger">
                            Remove Role
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <%} %>
</body>
</html>

Controller

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        AssignRolesModel model = new AssignRolesModel();
        model.lstAdmins = AdminList();
        model.lstUsers = UserList();
        return View(model);
    }
    [HttpPost]
    public ActionResult Assign(AssignRolesModel role)
    {
        string adminName = AdminList().Where(x => x.UserId == role.AdminId).Select(x => x.Name).FirstOrDefault();
        foreach (var user in role.lstUsers)
        {
            string userId = user.UserId;
            string name = user.Name;
            bool selected = user.SelectedUsers;
            string assignToAdmin = selected ? adminName : "";
            // Code for Update record in database.
        }
        role.lstAdmins = AdminList();
        return View("Index", role);
    }

    // Get Admin List From Database.
    public List<AdminModel> AdminList()
    {
        List<AdminModel> lstAdmins = new List<AdminModel>();
        lstAdmins.Add(new AdminModel { UserId = "1", Name = "Admin 1" });
        lstAdmins.Add(new AdminModel { UserId = "2", Name = "Admin 2" });
        lstAdmins.Add(new AdminModel { UserId = "3", Name = "Admin 3" });
        return lstAdmins;
    }

    // Get User List From Database.
    public List<UserModel> UserList()
    {
        List<UserModel> lstUsers = new List<UserModel>();
        lstUsers.Add(new UserModel { UserId = "1", Name = "User 1", SelectedUsers = true });
        lstUsers.Add(new UserModel { UserId = "2", Name = "User 2", SelectedUsers = false });
        lstUsers.Add(new UserModel { UserId = "3", Name = "User 3", SelectedUsers = false });
        lstUsers.Add(new UserModel { UserId = "4", Name = "User 4", SelectedUsers = true });
        return lstUsers;
    }

    public ActionResult RemoveRole(string id)
    {
        return RedirectToAction("Index");
    }
}

Model

public class AssignRolesModel
{
    public List<AdminModel> lstAdmins { get; set; }
    public List<UserModel> lstUsers { get; set; }
    public string AdminId { get; set; }
    public string UserId { get; set; }
    public int? CreatedBy { get; set; }
}
public class AdminModel
{
    public string UserId { get; set; }
    public string Name { get; set; }
}
public class UserModel
{
    public string UserId { get; set; }
    public string Name { get; set; }
    public bool SelectedUsers { get; set; }
    public string AssignToAdmin { get; set; }
}