I am trying to update a partial view using ajax, but for some reason its failing.
Controller:
[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")
}
});
});
Partial:
<%@ 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>
Master View:
<%@ 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>
Your partial view is full of errors.
Your controller action passes a
List<string>(orList<int>depending on the type of theSectionIdproperty) to this view:and yet in your partial view you are attempting to use some
item.SectionIdanditem.Description.Start by making your view strongly typed so that you have Intellisense showing you what you can and cannot use at compile-time: