我正在尝试使用ajax更新部分视图,但由于某种原因它失败了。
控制器:
[HttpPost()]
public ActionResult DisplaySections(string id)
{
DataContext db = new DataContext();
var Data = (from p in db.vwData.Where(a => a.CourseId == id)
group p by p.SectionId into g
select g.Key).ToList();
return PartialView("DisplaySections", Data);
}
的Ajax:
$('#CourseId').focusout(function (e) {
e.preventDefault();
var link = '/Course/DisplaySections';
$.ajax({
type: 'POST',
url: link,
data: { id: $('#CourseId').val() },
dataType: 'html',
success: function (result) {
$("#partial").html(result);
},
error: function (result) {
alert("Failed")
}
});
});
部分:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%@ Import Namespace="Course.Models" %>
<table>
<% if (Model != null)
foreach (var item in Model) {
if (item == null) continue; %>
<tr>
<td>
<%: item.SectionId%>
</td>
<td>
<%: item.Description%>
</td>
</tr>
<% } %>
</table>
主视图:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<%@ Import Namespace="Course.Models" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Course - Sections
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div style="text-align: left; height: 202px;">
<table>
<tr>
<th>Course Id</th>
<td><input type="text" name="CourseId" id="CourseId"/></td>
</tr>
<tr>
<th>Course Name</th>
<td><input type="text" name="CourseName" id="CourseName"/></td>
</tr>
</table>
<div id="partial">
<% Html.RenderPartial("DisplaySections"); %>
</div>
</div>
</asp:Content>
答案 0 :(得分:1)
您的部分视图充满了错误。
您的控制器操作会将List<string>
(或List<int>
,具体取决于SectionId
属性的类型)传递到此视图:
[HttpPost()]
public ActionResult DisplaySections(string id)
{
DataContext db = new DataContext();
List<string> data =
(from p in db.vwData.Where(a => a.CourseId == id)
group p by p.SectionId into g
select g.Key).ToList();
return PartialView("DisplaySections", data);
}
但在您的部分视图中,您尝试使用某些item.SectionId
和item.Description
。
首先强调您的视图类型,以便您在Intellisense中显示您在编译时可以使用和不能使用的内容:
<%@ Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<List<string>>"
%>
<table>
<% if (Model != null) { %>
<% foreach (string item in Model) { %>
<% if (item == null) continue; %>
<tr>
<td>
<%: item %>
</td>
</tr>
<% } %>
<% } %>
</table>
答案 1 :(得分:0)
让我们尝试一些事情: