2017-07-14 4 views
0

Ich habe eine MVC-Ansicht, die ein Jahr Drop-down und eine Schaltfläche zum Senden enthält. Standardmäßig werden die Daten des aktuellen Jahres (d. H. 2017 Jahr) beim Laden der Seite geladen und es funktioniert gut, aber wenn ich ein anderes Jahr aus dem Dropdown auswähle, wird die Ansicht nicht aktualisiert. Bitte beachten Sie den Code unten:Aktualisieren MVC View on button klicken

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

Antwort

2

Sie haben einen Teil verpasst, als Sie eine Antwort verarbeiten müssen, dafür können Sie einen Rückruf unter success hinzufügen und die Antwort (HistoricData) an die entsprechende Stelle einfügen. Auch in Ihrem Fall besser GET zu verwenden, anstatt 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); },     
     }); 
+0

Und fügt [Httppost] Tag in Ihrer Controller-Methode –

+0

Und denken Sie daran zurückzukehren 'PartialView' anstatt' View' von dieser Aktion. Andernfalls wird das gesamte Layout in der AJAX-Antwort gerendert. –

+0

@ IIya.Sulimanov - Sorry, ich habe vergessen, die modellbezogenen Details hinzuzufügen und nur den Code hinzugefügt. – user972255