How to pass selected dropdownlist value to Ajax.Ac

2019-06-05 06:49发布

问题:

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