开发者

Using AJAX to return SelectList selected value

At risk of asking the obvious... I need to use AJax.ActionLink to send the current value of a SelectList back to my controller. How do I do that?

Below is part of my current View. I need to replace "15" with the current value of the SelectList.

<% If Model.ShoppingListNames IsNot Nothing Then%>
    <%: Html.DropDownList("开发者_运维知识库ShoppingListNames", Model.ShoppingListNames)%>
    <%: Ajax.ActionLink("Add to List", "AdjustMaterials", "Docs",
                        New With {.userDocId = 15, .prodId = Model.ID, .quantity = 1},
                        New AjaxOptions With {.OnSuccess = "handleUpdate"})%>
<% End If%>

Using the "answer" to use Ajax.BeginForm instead of Ajax.ActionLink, below is part of the View I ended up with.

        <% If Model.ShoppingListNames IsNot Nothing Then%>
            <% Using Ajax.BeginForm("AdjustMaterials", "Docs", New With {.prodId = Model.ID}, New AjaxOptions With {.UpdateTargetId = "result-message"})%>
                <%: Html.DropDownList("userDocId", Model.ShoppingListNames)%>
                <input value ="Add to List" type ="submit"/>
            <% End Using%>
            <div id="result-message"></div>
        <% End If%>

And below is the controller. Note that the prodId parameter is specified in the call to Ajax.BeginForm but the userDocId parameter is specified by the current value of the SelectList within the form.

<HttpPost()>
Function AdjustMaterials(ByVal userDocId As Integer, ByVal prodId As Integer,
    Optional ByVal quantity As Integer = 1, Optional ByVal itemTag As String = Nothing) As ActionResult

 ' Do stuff...
End Function


One way to achieve this is to put the dropdownlist inside an AJAX form and replace the AJAX link with submit button. When the button is clicked it will submit the formed to the desired action using AJAX.


The best is to use jquery, something like this:

$(document).ready(function () {
  $('#ShoppingListNames').change(function() {
    var value = $('#ShoppingListNames > option:selected').attr('Value');
    if(value != '') {
      $.ajax({
        type: 'GET',
        contentType: 'application/json;charset=utf-8',
        url: '<%: Url.Action("AdjustMaterials", "Docs", new {prodId = Model.ID, quantity = 1}) %>?=userDocId=' + value,
        data: '',
        dateType: 'json',
        success: function (data) {
          ...
        }
      }
    }
  }
}

And the controller:

    public ActionResult AdjustMaterials(string prodId, string quantity, string userDocId)
    {
        ...
        return Json("...", JsonRequestBehavior.AllowGet);
    }

JsonRequestBehavior.AllowGet because I use GET, but not necesary if you use POST

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜