对Controller的Ajax调用在MVC 4中到空

时间:2016-05-17 19:57:13

标签: javascript jquery ajax asp.net-mvc-4

我试图在调用另一个select的onchange时填充一个select。以下是我建立的内容。我的GetLine ActionResult断点被命中,但参数breweryCode为null。那时的方法错误。我错过了什么?

控制器:

   public ActionResult Index()
    {
        List<Brewery> breweries = BuildMockBrewery();
        ViewBag.Breweries = new SelectList(breweries.AsEnumerable(), "BreweryCode", "BreweryDescription");
        return View();
    }

    public ActionResult GetLine(string breweryCode)
    {
        List<PackagingLine> packagingLines = BuildMockLine(breweryCode);
        SelectList pLine = new SelectList(breweryCode, "LineNumber", "Descriptions", 0);
        return Json(pLine);
    }

Index.cshtml:

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script type="text/javascript">
    function GetLine(_breweryCode) {
        var url = '/Report/GetLine/';

        $.ajax({
            url: url,
            data: { breweryCode: _breweryCode },
            cache: false,
            type: "POST",
            success: function (data) {
                alert('called');
                var markup = '<option value="0">Select Line</options>';
                for (var i = 0; i < data.length; i++) {
                    markup += '<option value="' + data[i].Value + '">' + data[i].Text + '</options';
                }
                $('#LineSelect').html(markup).show();
            },
            error: function (response) {
                alert('fail' + ' ' + _breweryCode);
            }
        });
    }
</script>
<div id="report-description">
    @using (Html.BeginForm("Index", "Report", FormMethod.Post))
    {    
        @Html.DropDownList("BreweryCode", (SelectList)ViewBag.Breweries, "Select Brewery", new { @class = "ui-select", @ID = "BrewerySelect", @onchange = "javascript:GetLine(this.Value);" })

        <select class="ui-select" id="LineSelect" name="ReportSelect">
                                 </select>
     }

2 个答案:

答案 0 :(得分:1)

@onchange属性中,将this.Value更改为this.value

尝试添加

[HttpPost]
public ActionResult GetLine(string breweryCode)
{
    List<PackagingLine> packagingLines = BuildMockLine(breweryCode);
    SelectList pLine = new SelectList(breweryCode, "LineNumber", "Descriptions", 0);
    return Json(pLine);
}

因此GetLine可以处理POST请求

答案 1 :(得分:0)

请同时添加数据类型:

dataType:'html'或dataType:'json'

并在控制器中添加 http方法 d

[HttpPost]
public ActionResult GetLine(string breweryCode)
{

}

另外,请确保值_breweryCode是否在函数

下面
function GetLine(_breweryCode)
{
}

将以下代码作为样本

$.ajax({
    type: "POST",
    url: your url,
    dataType: 'json',
    data: JSON.stringify({ id: '2' }),
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        alert('hello');
    }
});