[英]Render a PartialView in a div without postback
我知道這個問題已被問過很多次,但無論我嘗試什么,我都無法讓它發揮作用。 我有一個 actionResult 接受三個參數並返回一個局部視圖。 現在我想做的是獲取三個元素的值並使用它們在 div 中重新渲染視圖。 我嘗試使用捕獲的數據成功呈現 div,但我無法弄清楚 jquery 做錯了什么
在腳本文件中包含了我嘗試的最后一件事(盡管在每次嘗試中,在放棄之前都有一些調整)
這是主視圖中的 RenderAction(有效)
<div id="tables">
@{ Html.RenderAction("_Tables", new { date = "5/10/2019", time = "13:00", seats = "1" });}
</div>
返回所述 Partial 的操作結果
public ActionResult _Tables(string date, string time, int seats)
{
return PartialView("_Tables", checkTables(date,time,seats));
}
最后是腳本(searchTable 是字段附近的一個按鈕。它們的值被成功捕獲但加載不起作用)
$('#searchTable').click(function () {
var date = document.getElementById("datepicker").value;
var time = document.getElementById("time").value;
var seats = document.getElementById("seats").value;
alert(date);
//var data = JSON.stringify({
// 'date': date,
// 'time': time,
// 'seats': seats
//});
//$.ajax({
// type: "POST",
// url: '/Home/_Table/',
// data: data,
// dataType: "html",
// success: function (result) { success(result); }
//});
//function success(result) {
// alert(result);
// $("#tables").html(result);
// $("#tables").load("#tables")
//};
//$.ajax({
// url: "/Home/_Table",
// type: "GET",
// contentType: "application/json; charset=utf-8",
// data: data,
// success: function (data) {
// $('#target').html(data); // loading partialView into div
// }
//});
//$('#tables').load('@{ Html.RenderAction("_Tables", new { date = "' + date + '", time = "' + time + '", seats = "' + seats + '" });}');
$('#tables').load('@Url.Action("_Tables","Home")', { 'date': date, 'time': time, 'seats': seats });
alert(time);
//alert('@{ Html.RenderAction("_Tables", new { date = "' + date + '", time = "' + time + '", seats = "' + seats + '" });}');
});
我知道問題在於我缺乏了解,但我沒有時間研究 ajax。 我的實習是基於在最后期限內“弄清楚”
我在您的代碼中看到一條注釋行:
$("#tables").html(result);
這就是你所需要的。 您應該使用從控制器返回的所有局部視圖 html 填充您的 div。
假設您有一個帶有id
表的div
<div id="tables">
您可以使用以下方法根據您的參數附加部分視圖內容
$.ajax({
url: "/Home/_Tables?date=" + val + "&time="+ val +"&seats="+seats,
type: "POST",
cache: false,
success: function (result) {
$("#tables").empty();
$("#tables").html(result);
},
error: function () {
$("#tables").empty();
}
});
這將是主要視圖 ajax function.and 在 controller 中執行以下操作
public ActionResult _Tables(string date, string time,string seats)
{
// here you can provide model,any viewbag values etc to the partial view and you will get corresponding html result
return PartialView("Yourpartial ViewName");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.