[英]Change view using ajax on drop-down list change event
當用戶更改下拉列表的選項時,我需要使用 ajax 更改同一頁面中的視圖。
到目前為止,在我看來,我有下拉列表
<div class="wrapper">
<div>
<label>Get cars per people </label>
@Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { @id = "ddlChangeID" })
</div>
<div class="box box-success">
<div class="box-body">
<div>
<canvas id="myChart"></canvas>
</div>
</div>
</div>
</div>
然后在一個腳本中(我從另一個問題中找到)
$(document).ready(function () {
$("#ddlChangeID").change(function () {
var strSelected = "";
$("#ddlChangeID:selected").each(function () {
strSelected += $(this)[0].value;
});
var url = "/Cars/Index/" + strSelected;
$.post(url, function (data) {
});
});
})
在 controller 中,我使用 ViewBag 值來保存下拉列表值,以及使用 ViewBag 值再次加載到不同腳本中的圖形所需的任何其他內容。 我設法傳遞了選定的值(strSelected),但視圖沒有重新加載新數據。
我應該如何進行 ajax 事件?
通過調用如下操作結果來更改腳本 ajax 調用
$("#ddlChangeID").change(function () {
$.ajax({
url: "/Controller/ActionHtml?id="+$('#ddlChange').val(),
type: "POST",
cache: false,
success: function (result) {
$("#myChart").html(result);
},
error: function () {
$("#myChart").empty();
}
});
});
在 controller 中,actionresult 將如下所示,返回 html 部分視圖,您需要 append
public ActionResult ActionHtml(string id)
{
//Here you can load the data based on the id,pass model to the patial views etc
ViewBag.id = id;
return PartialView("~/Views/Shared/myhtml.cshtml");
}
myhtml.cshtml
將是帶有 html 內容的部分視圖 //content is dummy, 根據需要更改內容
<!DOCTYPE html>
<html>
<body>
<p>Enter some text in the fields below, then press the "Reset form" button to reset the form.</p>
<form id="myForm">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
</form>
所以我改變了
@Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { @id = "ddlChangeID" })
至
@Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { @onchange = "ChangeOption()" })
還向主 div 添加一個 id。 和腳本
function ChangeOption() {
var id = $('#ddlChange').val();
$.ajax({
url: '/Cars/Index',
type: "GET",
data: { Id: id },
success: function (data) {
$('#wrapAll').html(data);
}
});
}
它似乎工作。 現在唯一的問題是 css 壞了。 它將圖形和下拉列表推到右側,破壞了功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.