How to pass selected dropdownlist value to Ajax.ActionLink in MVC 4?

流过昼夜 提交于 2020-01-03 04:23:07

问题


I am trying to pass a Form value "CustomerID" (i.e.dropdownlist selected value) using Ajax.Actionlink in MVC 4. Can someone tell me what I am doing wrong here?

<div class="editor-label">
    @Html.LabelFor(model => model.CustomerID, "Customer Name")
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.CustomerID, Model.CustomersList, "-- Select --")
    @Html.ValidationMessageFor(model => model.CustomerID)
</div>

<div id="ApptsForSelectedDate">
   @Ajax.ActionLink("Click here to view appointments",
                    "AppointmentsList",
                    new {id = Model.CustomerID},
                    new AjaxOptions
                    {
                       UpdateTargetId = "ApptsForSelectedDate",
                       HttpMethod = "GET",
                       InsertionMode = InsertionMode.Replace,
                       LoadingElementId = "progress"
                    }
                  )            
</div>
<div id="progress">
   <img src="../../Images/ajax-loader.gif" alt="loader image" />
</div>

My controller method looks like this:

public PartialViewResult AppointmentsList(int id)
{   ... }

回答1:


You should use an Ajax.BeginForm and put the dropdown inside the form. This way the value will be automatically passed.

Unfortunately since you cannot nest html forms if you already have another form wrapping this markup you cannot use a nested form.

In this case you could use a normal link:

@Html.ActionLink(
    "Click here to view appointments", 
    "AppointmentsList", 
    null, 
    new { id = "applink" }
)

and in a separate javascript file AJAXify it and append the necessary information to the query string by reading the selected dropdown value at the moment the AJAX request is sent:

$(function() {
    $('#applink').click(function() {
        $('#progress').show();
        $.ajax({
            url: this.href,
            type: 'GET',
            data: { id: $('#CustomerID').val() },
            complete: function() {
                $('#progress').hide();
            },
            success: function(result) {
                $('#ApptsForSelectedDate').html(result);
            }
        });
        return false;
    });
});


来源:https://stackoverflow.com/questions/12135843/how-to-pass-selected-dropdownlist-value-to-ajax-actionlink-in-mvc-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!