我刚开始使用Mvc Framework,我想显示包含产品详细信息的部分视图。主视图包含用户将点击的产品名称,产品的详细信息将列在同一页面上我的局部视图是在新页面上打开,第一次页面加载它默认显示第一个产品细节,我已经尝试了很多,看到其他链接但这个问题仍然是相同的..请帮助解决这个问题。我正在使用的完整代码如下所示。
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MvcFirstMVCApp.Models;
namespace MvcFirstMVCApp.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
AuthorContactEntities dbEntities = new AuthorContactEntities();
public ActionResult Index()
{
return View(dbEntities.tbl_product.ToList());
}
public ActionResult PartialView(int id)
{
var query = dbEntities.tbl_product.First(c => c.ProductId == id);
return PartialView("PartialView", query);
}
}
}
Index.cshtml
@model List<MvcFirstMVCApp.Models.tbl_product>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<script src="@Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("div.product a").click(function (e) {
alert("clicked");
var url = this.ref;
$get(url, {}, function (data) {
$('div.productdetail').html(data);
});
});
return false;
});
</script>
</head>
<body>
<div class="product">
<ul class="list">
@foreach (var item in Model)
{
<li><a href="@Url.Action("PartialView", "Home", new { id = item.ProductId })">
@item.ProductName</a></li>
}
</ul>
<div class="productdetail">
@{Html.RenderPartial("PartialView",Model.FirstOrDefault());}
</div>
</div>
</body>
</html>
PartialView.cshtml
@model MvcFirstMVCApp.Models.tbl_product
<label>@Model.ProductDesc</label>
Author_Contact_DetailsModel.edmx
表名称:tbl_product
ProductId
ProductName
ProductDesc
答案 0 :(得分:0)
这是预期的行为。
您正在此处呈现指向您的操作方法的链接:
<li><a href="@Url.Action("PartialView", "Home", new { id = item.ProductId })">
@item.ProductName</a></li>
单击该按钮将使浏览器导航到您的操作方法,该方法将返回部分视图。该部分视图没有布局。您的View似乎也没有布局。
这听起来很苛刻......但你应该重新审视你的MVC资源并重新阅读Partial Views的工作原理。它们不是神奇的动态加载视图..如果你想要你需要调查AJAX。
答案 1 :(得分:0)
$("div.product a").click(function (e) {
var url = this.ref;
$get(url, {}, function (data) {
$('div.productdetail').html(data);
});
// Return here to prevent click event from opening new page
return false;
});
单击锚标记,打开一个呈现局部视图的新页面。您需要阻止锚的默认行为。
您可以添加return false;
来执行此操作。
答案 2 :(得分:0)
调用e.preventDefault();在onclick处理程序中:
$("div.product a").click(function (e) {
e.preventDefault();
alert("clicked");
var url = this.ref;
$get(url, {}, function (data) {
$('div.productdetail').html(data);
});
});
答案 3 :(得分:0)
看这篇文章。如建议的那样在_layout中添加一行代码为我解决了这个问题。