Reputation: 1828
I have a MVC view which contains a year dropdown and a submit button. By default the current year (i.e. 2017 year) data is loaded on page load and it works fine but when I select some other year from the dropdown its not refreshing the view. Please see the code below:
HistoricData.cshtml
<div class="form-group">
<label for="year">Year</label>
<select id="year" name="year" class="form-control">
<option>2017</option>
<option>2016</option>
<option>2015</option>
<option>2014</option>
<option>2013</option>
</select>
</div>
<button id="btnData" class="btn btn-default" onclick="GetData()">Get Data</button>
<table id="tblData" class="table table-condensed table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Date/Time</th>
</tr>
</thead>
<tbody>
@foreach (var d in Model.AllData)
{
<tr>
<td>@d.ID</td>
<td>@d.Name</td>
<td>@d.DateTime</td>
</tr>
}
</tbody>
</table>
Script:
function GetData() {
$.ajax({
type: "POST",
url: '@Url.Action("GetData")',
data: JSON.stringify({
year: $("#year option:selected").text()
}),
contentType: "application/json; charset=utf-8"
});
}
Controller: HistoricDataController.cs
//this gets called on page load
public ActionResult HistoricData()
{
var year = 2017;
return View(GetHistoricData(year));
}
//trying to call this method to refresh the data with the year selected
public ActionResult GetData(int year)
{
var model = GetHistoricData(year);
return View("HistoricData", model);
}
private SomeData GetHistoricData(int year)
{
return SomeData;
}
Upvotes: 0
Views: 1688
Reputation: 7836
You missed a part when you have to handle response, for that you can add callback on success
and insert response (HistoricData
view) to relevant place. Also in your case better to use GET
rather than POST
$.ajax({
type: "POST",
url: '@Url.Action("GetData")',
data: JSON.stringify({
year: $("#year option:selected").text()
}),
contentType: "application/json; charset=utf-8",
success: function(data) { $("#somePlace").html(data); },
});
Upvotes: 2