2017-06-28 90 views
0

我有一個下拉選擇id StaffId。我正在做的是一旦一個項目被選中,我想通過StaffId傳遞給控制器​​,以使用staffId獲取數據庫中的記錄。這會在頁面加載時給出錯誤,而不會將StaffId傳遞給控制器​​。下面是摘錄MVC5阿賈克斯更新

控制器

[HttpPost] 
      public PartialViewResult GetStaffPosts(int? id) 
      { 

       var sPost = db.StaffPosts.Where(a => a.StaffId == id.Value); 
       return PartialView(sPost.ToList()); 

      } 

    <div id="divPartialView"> 
    @{Html.RenderPartial("GetStaffPosts");} 
    </div> 

<script type="text/javascript"> 
    $(document).ready(function() { 
     $("#StaffId").change(function (event) { 
      var options = {}; 
       options.url= "/StaffPost/GetStaffPosts/" + $(this).val(), 
       options.data= { id: $(this).val() }, 
       options.cache= false, 
       optionstype= "POST", 
       options.dataType= "html", 

       options.success= function (data, textStatus, XMLHttpRequest) { 
        $("#divPartialView").html(data); // HTML DOM replace 
        $.ajax(options); 
       } 
      }); 
     }); 

</script> 
+0

您可以在此處添加控制器代碼嗎? – hasan

+0

爲什麼你用HttpPost代替HttpGet,你試圖從db中獲取數據,在這種情況下你應該使用[HttpGet]。我會建議使用jquery load方法來解析你的分數視圖與數據庫數據到目標html元素 – hasan

回答

0

您當前的代碼實際進行的更改事件Ajax調用,因爲要調用的$.ajax(options);調用內部的選項成功回調對象。您沒有在更改事件中調用$ .ajax方法!

這應該工作(假設您的控制器代碼返回200響應)

$("#StaffId").change(function (event) { 
     var options = {}; 
     options.url= "/StaffPost/GetStaffPosts/" + $(this).val(), 
     options.data= { id: $(this).val() }, 
     options.cache= false, 
     options.type= "POST", 
     options.dataType= "html", 
     options.success= function (data, textStatus, XMLHttpRequest) { 
       $("#divPartialView").html(data); // HTML DOM replace 

     } 
     $.ajax(options); 
}); 

您還可以使用$.post方法簡化您的代碼。

$("#StaffId").change(function() { 

    $.post("/StaffPost/GetStaffPosts/",{ id: $(this).val() } ,function (data) { 
      $("#divPartialView").html(data); 
    }); 

}); 

甚至使用$.load方法和一個襯墊

$("#StaffId").change(function(event) { 

    $("#divPartialView").load("/StaffPost/GetStaffPosts/", { id: $(this).val() }); 

}); 
+0

這工作,但我已決定使用json – Diin

0

嗨只要把你的Ajax調用成功功能之外,並像下面的代碼的URL,然後再試一次

您更改的代碼:

<script type="text/javascript"> 
    $(document).ready(function() { 
     $("#StaffId").change(function (event) { 
      var options = {}; 


       options.url= "../StaffPost/GetStaffPosts, 


       options.data= { id: $(this).val() }, 
       options.cache= false, 
       optionstype= "POST", 
       options.dataType= "html", 
       options.success= function (data, textStatus, XMLHttpRequest) 
       { 
        $("#divPartialView").html(data); // HTML DOM replace 

       } 


       $.ajax(options); 


      }); 
     }); 

</script>