我試圖在我的視圖中顯示一個下拉串列,并且我能夠在下拉串列中生成串列項,一旦選擇了一個專案,我就會嘗試收集所選專案的詳細資訊并將其顯示在同一個視圖中。
在我的控制器中,我得到了所選專案的命中,我的 jquery 正確地將專案 ID 重定向到 ActionMethod 并填充模型并回傳視圖,但資料沒有顯示在視圖中。
我的索引視圖:
@model PWBMS.WebUI_1.Viewmodels.CustomerViewModel
<div class="row">
<h3 class="col-md-3">
<i class="glyphicon glyphicon-user"></i>
<strong>
Customer
<span id="cidd"> @Html.DropDownListFor(model => model.CustomerId, new SelectList(ViewBag.Customers, "CustomerId", "ShortName"), "Select Customers", htmlAttributes: new { @class = "form-control rtscustomtextboxmiddle", @id = "custId" })</span>
</strong>
</h3>
</div>
@if(Model != null)
{
@Model.ShortName
}
我的 jQuery 對下拉串列中的選定項進行系結:
@section scripts
{
<script type="text/javascript">
$(document).ready(function () {
$("#cidd").change(function () {
var y = $("#custId option:selected").val();
$.ajax({
url: "@Url.Action("Index", "Customer3")",
method: "get",
async: "false",
data: { id: y }
});
});
});
</script>
}
我的控制器:
public ActionResult Index(int? id)
{
if(id is null)
{
ViewBag.Customers = db.Customers.OrderByDescending(o => o.CustomerId).ToList();
return View();
}
var vm1 = db.Customers.SingleOrDefault(x => x.CustomerId == id);
ViewBag.Customers = db.Customers.OrderByDescending(o => o.CustomerId).ToList();
CustomerViewModel cvm = new CustomerViewModel
{
CustomerId = vm1.CustomerId,
ShortName = vm1.ShortName
};
return View( cvm);
}
擊中資料的螢屏截圖:
我的模型值的第二個螢屏截圖


我希望這不會因為重復而關閉,因為我為我的獨特情況尋找解決方案但我找不到。
我什至嘗試將結果集放在區域視圖中,它正在獲得正確的結果,但仍然沒有顯示它。
我知道我做錯了什么,但不確定我做錯了什么。請幫我指出我的錯誤。謝謝。
uj5u.com熱心網友回復:
實際上,您正在發出一個您不在視圖上處理的 ajax 請求,有兩種方法可以解決它,一種只是在更改事件上發布表單或重定向到同一視圖
document.location.href = '/controllerName/actionName/' y;
如果您真的想使用 ajax,請更新您的代碼,如下所示
<div class="result"></div>
$.ajax({
url: "@Url.Action("Index", "Customer3")",
method: "get",
async: "false",
data: { id: y }
})
.done(function(r) {
$('.result').html(r.ShortName);
})
您還需要更新操作
if(id.HasValue)
{
var vm1 = db.Customers.SingleOrDefault(x => x.CustomerId == id.Value);
ViewBag.Customers = db.Customers.OrderByDescending(o => o.CustomerId).ToList();
CustomerViewModel cvm = new CustomerViewModel
{
CustomerId = vm1.CustomerId,
ShortName = vm1.ShortName
};
return Json(cvm, JsonRequestBehavior.AllowGet);
}
else
{
ViewBag.Customers = db.Customers.OrderByDescending(o => o.CustomerId).ToList();
return View();
}
請注意,在使用 Ajax 請求時,與 ViewBag 相關的內容將不起作用,上面的代碼只是為了讓您了解,如果您還想更新這些值,只需相應地創建一個 ViewModel 并以 json 形式回傳。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/503900.html
標籤:C# asp.net-mvc asp.net-mvc-4 模型视图控制器 asp.net-mvc-5
上一篇:ASP.NETMVC應用程式-突出顯示時態表記錄串列中每條記錄之間的差異
下一篇:切換li后洗掉的串列元素
