0

我正在尝试使用 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);
}

阿贾克斯:

$('#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>
4

2 回答 2

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.SectionIditem.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>
于 2012-07-11T05:43:21.583 回答
0

让我们尝试几件事:

  1. 尝试不指定数据类型。把它放在外面。
  2. 尝试使 url: 指向绝对路径(使用 Url.Action 可能吗?)而不是相对路径。
于 2012-07-10T22:47:21.977 回答