todd.pund todd.pund - 6 months ago 17
Javascript Question

Ajax call to Controller arrives empty in MVC 4

I'm trying to populate one select when the onchange of another select is called. Below is what I have built. My GetLine ActionResult breakpoint is being hit, but the parameter breweryCode is null. The method errors at that point. What am I missing?

Controller:

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

Answer

In your @onchange attribute, change this.Value to this.value

Try add

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

so GetLine can be able to process POST request

Comments