[英]Ajax does not retrieves data in partial view in mvc
我的下面的代碼我用ajax調用部分視圖但是當我點擊產品名稱的鏈接時,不會通過ajax檢索該產品的描述並執行ajax的錯誤。 我正在檢索用戶在同一頁面上選擇的項目的詳細信息,但不會檢索它。 請提出任何建議,因為我是MVC的新手。 謝謝...
Create.cshtml
@model List<PartialView.Models.tbl_product>
<!DOCTYPE html>
<html>
<head>
<title>Create</title>
<script src="@Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.msg').click(function () {
var id = this.id;
$.ajax({
url: "/Category/Display",
data: { data: id },
success: function (mydata) {
$("#link").empty().append(mydata);
},
error: function (mydata) { alert("error"); },
type: "POST"
});
return false;
});
});
</script>
</head>
<body>
@foreach (var item in Model)
{
<a class="msg" href="#" id="@item.ProductId">@item.ProductName</a>
}
<div id="link">
</div>
</body>
</html>
ClicksUs.cshtml(PartialView)
@model List<PartialView.Models.tbl_product>
@foreach(var items in Model)
{
@items.ProductDesc
}
CategoryController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PartialView.Models;
namespace PartialView.Controllers
{
public class CategoryController : Controller
{
dbEntities dbentity = new dbEntities();
public ActionResult Create()
{
return View(dbentity.tbl_product.ToList());
}
public ActionResult Display(int data)
{
var query = dbentity.tbl_product.First(c => c.ProductId == data);
return PartialView("ClicksUC", query);
}
}
}
您的Details
控制器操作在此處選擇單個元素(因為您正在調用.First()
):
public ActionResult Display(int data)
{
var query = dbentity.tbl_product.First(c => c.ProductId == data);
return PartialView("ClicksUC", query);
}
因此查詢變量的類型是tbl_product
而不是List<tbl_product>
。
另一方面,你的部分模型是List<PartialView.Models.tbl_product>
,這顯然是錯誤的。
您的部分模型應該是單個tbl_product
:
@model PartialView.Models.tbl_product
@Model.ProductDesc
哦,其他人對你的部分名字中的拼寫錯誤說了些什么。
您可以解決的代碼中有三個問題。
type: "POST"
,你應該改為type: "GET"
。 嘗試將代碼更改為:
public ActionResult Display(int data)
{
// using First() would have caused you an error in the view if not found
// still not perfect below, but a step closer
var query = dbentity.tbl_product.FirstOrDefault(c => c.ProductId == data);
// You had ClicksUC, rather than ClicksUS
return PartialView("ClicksUS", query);
}
我還強烈建議您為數據創建一個ViewModel
,而不是從數據庫傳遞對象,因為這樣可以准確控制應該查看的數據以及應該如何格式化等。
[編輯]另外,正如Darin所說,基於要重新編譯的單行,您應該將部分視圖模型類型更改為:
@model PartialView.Models.tbl_product
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.