单击按钮刷新MVC视图

时间:2017-07-14 20:32:06

标签: asp.net-mvc-4

我有一个MVC视图,其中包含一年下拉列表和一个提交按钮。默认情况下,当前年份(即2017年)数据在页面加载时加载,并且工作正常,但是当我从下拉列表中选择其他年份时,它不会刷新视图。请参阅以下代码:

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>

脚本:

function GetData() {   
            $.ajax({
                type: "POST",
                url: '@Url.Action("GetData")',
                data: JSON.stringify({
                    year: $("#year option:selected").text()
                }),
                contentType: "application/json; charset=utf-8"                
            });
        }

控制器: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;
}

1 个答案:

答案 0 :(得分:2)

您必须处理响应时错过了一部分,因为您可以在success上添加回调并将响应(HistoricData视图)插入相关位置。在您的情况下,最好使用GET而不是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); },                
        });