I am using paged list and calling ajax when i click on next that is working.The problem is when i click on previous or page number that does not call ajax.I need to use ajax call in paged List rather than my own ajax.
public ActionResult ApplicantsRecord(int? page)
{
List<ApplicantsRecord> ar = new List<ApplicantsRecord>();
ApplicantsRecord a = new ApplicantsRecord();
List<ApplicantsRecordDetailViewModel> apvmlist = new List<ApplicantsRecordDetailViewModel>();
ApplicantsRecordDetailViewModel apvm = new ApplicantsRecordDetailViewModel();
//ar = db.ApplicantsRecords.ToList();
var groupedAR = db.ApplicantsRecords.GroupBy(x => x.SessionId)
.Select(y => new
{
SessionId = y.Key,
ApplicationsRecords = y.FirstOrDefault(),
}).ToList().OrderByDescending(x => x.ApplicationsRecords.LoginDate);
foreach (var i in groupedAR)
{
ar.Add(i.ApplicationsRecords);
}
int pageNumber = (page ?? 1);
if(Request.IsAjaxRequest())
{
return PartialView("_ApplicantsRecord", ar.ToPagedList(pageNumber, 10));
}
return View(ar.ToPagedList(pageNumber, 10));
}
code of view
<div id="targetContainer">
#Html.Partial("_ApplicantsRecord",Model);
</div>
code for ajax
var npage =2;
$(document).ready(function () {
$('#container').click(function () {
$.ajax({
type: "GET",
traditional: true,
cache: false,
url: '/Testing/ApplicantsRecord/',
data:{page:npage}
})
.success(function (html) {
UpdatePage(html);
})
.error(function () {
});
return false;
});
});
function UpdatePage(html) {
$("#targetContainer").empty().html(html);
newpage = $('#newpage').val();
npage = parseInt(npage)
npage = npage + 1;
$('#newpage').val(npage);
}
and here is the partial view
i got it i was not using jquery unobtrusive in my jquery bundle
i downlloaded jquery unobtrusive ui using Nuget package and added in a new bundle
then include that bundle in my _Layout view instead of jquery bundle it started work
and changed the patrial view code to this one
#model IPagedList<ApplicantsRecord>
<div id="container">
<div class="pagedList">
#Html.PagedListPager(Model, page => Url.Action("ApplicantsRecord", new { page = page }), PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions()
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "targetContainer"
}))
</div>
</div>
<table>
<thead>
<tr>
<th width="200" align="center">User Name</th>
<th width="200" align="center">Login Date Time</th>
<th width="100" align="center">Details</th>
</tr>
</thead>
<tbody>
#foreach (var group in Model.GroupBy(x => x.UserName))
{
<tr class="group-header">
<td colspan="6">
<span class="label label-info">Applicant : #group.Key</span>
<span class="label label-success">Total Test Taken: #group.Count()</span>
</td>
</tr>
foreach (var item in group)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.UserName)</td>
<td>#Html.DisplayFor(modelItem => item.LoginDate)</td>
<td>#Html.ActionLink("Details", "ApplicantsRecordDetail", new { id = item.SessionId })</td>
</tr>
}
}
</table>
and the code of View to this one
#model IPagedList<ApplicantsRecord>
#using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
#{
ViewBag.Title = "ApplicantsRecord";
}
<h2>ApplicantsRecord</h2>
<p>
#Html.ActionLink("Back To List", "QuestionDetail") |
#Html.ActionLink("Live View ", "LiveView")
</p>
<div id="targetContainer">
#Html.Partial("_ApplicantsRecord",Model)
</div>
Related
I have an mvc5 action method that returns a jsonresult to a knockout mvvm.
On my development machine it works perfectly, but when I deploy to IIS, I get a 404 Not Found error.
When I used Google Chrome debugging tools, I get this message:
//http:localhost/Student/Register_For_Courses not found
Below is my code:
Controller Action
public JsonResult Register_For_Courses()
{
ScoreService ss=new ScoreService();
var courses = ss.FetchCoursesForSemesterRegistration().ToList();
return this.Json(courses, JsonRequestBehavior.AllowGet);
}
JavaScript file using Knockout
function Course(data) {
var self = this;
self.CourseId = ko.observable(data.CourseId);
self.CourseCode = ko.observable(data.CourseCode);
self.Title = ko.observable(data.Title);
self.CreditHour = ko.observable(data.CreditHour);
self.Level = ko.observable(data.Level);
self.Type = ko.observable(data.Type);
self.SessionId = ko.observable(data.SessionId);
self.SemesterId = ko.observable(data.SemesterId);
self.StudentId = ko.observable(data.StudentId);
self.ProgrammeCode = ko.observable(data.ProgrammeCode);
self.Semester = ko.observable(data.Semester);
self.IsOutStanding = ko.observable(data.IsOutStanding);
self.result = ko.observableArray(data.result);
return self;
}
//View Model
function CourseList(url) {
var self = this;
self.totalCreditHours = 0;
self.courses = ko.observableArray([]);
self.studentId = 0;
self.semesterId = 0;
$.ajax({
type: "GET",
url: 'Student/Register_For_Courses',
contentType: "application/json; charset=utf-8",
datatype: 'json',
traditional: true,
success: function (data) {
ko.utils.arrayForEach(data, function (data) {
self.courses.push(new Course(data));
});
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
self.totalCreditHours = ko.pureComputed(function () {
var total = 0;
ko.utils.arrayForEach(self.courses(), function (item) {
var value = parseInt(item.CreditHour());
total += value;
})
return total;
},this);
}
}
$(document).ready(function () {
ko.applyBindings(new CourseList());
});
MVC5 View
#{
ViewBag.Title = "Students' Course Registration";
Layout = "~/Views/Shared/_StudentLayout.cshtml";
}
<div class="container">
<div class="row">
<h4>Semester Course Registrations</h4>
<div class="col-md-6">
<table class="table table-condensed table-responsive">
<thead>
<tr>
<th>
CourseCode
</th>
<th>
Title
</th>
<th>
Credit Hour
</th>
<th>
Type
</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: courses">
<tr>
<td data-bind="text:CourseCode"></td>
<td data-bind="text:Title"></td>
<td data-bind="text:CreditHour"></td>
<td data-bind="text:Type"></td>
<td data-bind="ifnot:IsOutStanding">
<button data-bind="click:removeCourse" class="btn btn-danger">Remove</button>
</td>
</tr>
</tbody>
<tr>
<td><b>Total Units</b></td>
<td></td>
<td><b data-bind="text:tHour"></b></td>
</tr>
</table>
</div>
</div>
</div>
#section Scripts {
#Scripts.Render("~/Scripts/ViewModels/CourseRegistrationsVM.js")
}
Thank you for your kind and quick response.
I have trouble getting my partial view appear in the "div" when I click on a button. I can see that it fetches the data when I debug, but does not display it. Anybody that might now the problem?.
View
#model IEnumerable<ActiveDirectorySearch.Models.UserModel>
<div id="searchList">
<table>
#foreach (var user in #Model)
{
<tr>
<td>
<ul class="user" data-user-id="#user.DistinguishedName">
<li><b>#user.DisplayName</b></li>
<li><i>Cdsid:</i> #user.CdsId</li>
<li><i>Name:</i> #user.GivenName #user.SurName</li>
<li><i>Title:</i> #user.Title</li>
<li><i>Department:</i> #user.Department</li>
<li><i>MemberOf:</i> Groups</li>
<li class="userInfo">More Info</li>
<li>
</li>
</ul>
</td>
</tr>
}
</table>
<div class="col-md-6 col-md-offset-3 display-groups">
</div>
</div>
Controller
public ActionResult GetUserInfo(string searchTerm)
{
GroupRepository groupRepository = new GroupRepository();
var groups = groupRepository.FindGroups(searchTerm);
return PartialView(groups);
}
Script
<script>
$(function () {
$('.LoadGroupsViewButton').click(function () {
var self = this;
var $user = $(self).closest('.user');
var userDistinguisedName = $user.data("user-id");
$.ajax({
method: "GET",
url: 'Home/GetUserInfo',
data: { searchTerm: userDistinguisedName }
}).done(function (data) {
$(self).find('.display-groups').html(data);
});
});
});
</script>
change your code from
$(self).find('.display-groups').html(data);
to
$("#searchList").find('.display-groups').html(data);
as here 'self' is the DOM element that triggered the event because of this piece of code
var self = this;
So it will not find div having class 'display-groups'
I'm trying to remove items from a list that I created following This question. The add part of the functionality works just fine.
When I specify an event in the onclick event on the partial page I get a javascript error. "'Function Name' is undefined." Looking it over I think the onclick attribute isn't required if the jquery is working. However, even after updating it to work with the latest version of JQuery it isn't detecting a click event, or at least it isn't triggered.
Main_View just the relevant sections
<table id="pastSchoolContainer">
<tr>
<td>
<input type="button" id="addPastSchool" name="addPastSchool" value="Add School" />
</td>
</tr>
#foreach (var school in Model.SchoolsAttended)
{
Html.RenderPartial("_SchoolRemovablePartial", school, new ViewDataDictionary(ViewData)
{
TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "SchoolsAttended" }
});
}
</table>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(document).ready(function () {
$("#addPastSchool").click(function () {
$.ajax({
async: false,
url: '/Student/AddPastSchool',
}).success(function (partialView) {
$("#pastSchoolContainer").append(partialView);
return;
});
});
return;
});
$("#addPastSchool").on("click", ".deleteRow", function () {
$(this).parents("#pastSchool:first").remove();
return false;
});
</script>
}
_SchoolRemovablePartial
#model ScholarSponsor.Models.SchoolModel
#using ScholarSponsor.Helper
#using (Html.BeginCollectionItem("pastSchool"))
{
<tr id="pastSchool">
<td>
#Html.EditorForModel()
<br />
#*Delete*#
<input type="button" class="deleteRow" value="Remove School" onclick="remove()" />
</td>
</tr>
}
Extending Stephen's answer the remove function needs to be inside a function that runs when the document is ready. Also, the button shouldn't have an onclick attribute.
The relevant code sections look like this.
Main_View
<table id="pastSchoolContainer">
<tr>
<td>
<input type="button" id="addPastSchool" name="addPastSchool" value="Add School" />
</td>
</tr>
#foreach (var school in Model.SchoolsAttended)
{
Html.RenderPartial("_SchoolRemovablePartial", school, new ViewDataDictionary(ViewData)
{
TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "SchoolsAttended" }
});
}
</table>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(document).ready(function () {
$("#addPastSchool").click(function () {
$.ajax({
async: false,
url: '/Student/AddPastSchool',
}).success(function (partialView) {
$("#pastSchoolContainer").append(partialView);
return;
});
});
$("#pastSchoolContainer").on("click", ".deleteRow", function () {
$(this).closest(".pastSchool").remove();
return;
});
});
</script>
}
_SchoolRemovablePartial
#model ScholarSponsor.Models.SchoolModel
#using ScholarSponsor.Helper
#using (Html.BeginCollectionItem("pastSchool"))
{
<tr class="pastSchool">
<td>
#Html.EditorForModel()
<br />
<input type="button" class="deleteRow" value="Remove School" />
</td>
</tr>
}
First off I must say I have a bit of a brain teaser here. I may be a bit new to ASP.Net MVC4 but I have never attempted anything like this. The end goal is a type of tree view for partial pages in a standard page. Right now I am trying to use ajax to load a partial in a div while passing the users selection to the next view(it will than be used to narrow that pages results).
<div>
<div>
<form id="myForm" action="ScheduleZone" method="post">
<table class="table">
<tr>
<th>Store
</th>
</tr>
#foreach (ACS.Models.Tree rate in TempML.Tree)
{
<tr>
<td>#Html.DisplayFor(model => rate.Store)#Html.ActionLink("+", " ScheduleZone", rate, new { #class = "g" })
</td>
</tr>
}
</table>
</form>
</div>
<div class="div" id="mainDiv">
</div>
<div class="div" id="Zone">
</div>
<div class="div" id="Sell">
</div>
<div class="div" id="Meh">
</div>
<div class="div" id="Sk">
</div>
</div>
<script type="text/javascript">
$(".g").click(function () {
$("#mainDiv").load("/Home/Zone");
});
</script>
I can't seem to call the page in the div after calling the http post action. It returns just the partial view not in the div.
public ActionResult Zone(CommisionsTree tree)
{
string banner = "2";
CommissionDAO dao = new CommissionDAO();
DataSet commissionInfo = dao.GetCommissionRates(tree, banner);
ModelList ml = new ModelList();
foreach (DataTable Table in commissionInfo.Tables)
{
foreach (DataRow row in Table.Rows)
{
Tree commTree = new Tree();
commTree.Banner = Convert.ToInt32(banner);
commTree.Store = tree.Store;
foreach (DataColumn column in Table.Columns)
{
switch (column.ColumnName)
{
case "SCHED_ZONE":
commTree.ScheduleZone = row[column].ToString();
break;
default:
break;
}
}
ml.CommissionTree.Add(commTree);
}
TempData["TempModelList"] = ml;
}
return PartialView(ml);
}
You can replace your link + javascript with an AjaxLink
#Ajax.ActionLink("+", "Zone", "Home", new AjaxOptions() { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "mainDiv" }, htmlAttributes: new { #class="someClasses", id = "anId"})
In this case, the reason why it's following link after it's loading it's because your need to return false at the end of your javascript.
<script type="text/javascript">
$(".g").click(function () {
$("#mainDiv").load("/Home/Zone");
return false;
});
</script>
the page has 2 DropDownLists + a Textbox + a Submit Button.
On Submit it's supposed to choose and fill a partial view depending on what value is selected in the first DropDownList. I got it somewhat working; however, it will always return the pv in a new window instead of rendering it in the main view's div.
I am using MVC 3 + Telerik.
The most Important parts of the code:
VIEW - Updated
<script type="text/javascript">
function onMainDDL1Change(e) {
var combo = $("#SubDDL1").data("tComboBox");
combo.value("");
combo.reload();
}
function onSubDDL1DataBinding(e) {
var combo = $("#MainDDL1").data("tComboBox");
e.data = $.extend({}, e.data, { mainDDL1ID: combo.value() });
}
</script>
#using (Ajax.BeginForm("PartialGrid", "DataSearch", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "result", InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace }))
{
<table>
<tr>
<td>
#(Html.Telerik().ComboBox()
.Name("MainDDL1")
.AutoFill(true)
.DataBinding(binding => binding.Ajax().Select("LoadMainDDL", "DataSearch"))
.HighlightFirstMatch(true)
.ClientEvents(events => events.OnChange("onMainDDL1Change"))
)
</td>
</tr>
<tr>
<td>
#(Html.Telerik().ComboBox()
.Name("SubDDL1")
.DataBinding(binding => binding.Ajax().Select("LoadSubDDL1", "DataSearch"))
.HighlightFirstMatch(true)
.ClientEvents(events => events.OnDataBinding("onSubDDL1DataBinding"))
)
</td>
<tr>
<td>
#Html.TextBoxFor(o => o.sSearch1)
</td>
</tr>
<tr align="center">
<td colspan="4">
<input type="submit" class="t-button" value="Search" name="submit" />
</td>
</tr>
</table>
}
<div id="result">
</div>
Controller - Updated
[HttpPost]
//PartialView
public PartialViewResult PartialGrid(DataSearchModel voModel)
{
voModel.dtResultSet1 = DLA.DataSearchContext.getResultSet1(voModel.MainDDL1, voModel.SubDDL1, voModel.sSearch1);
return PartialView("_TPRCL", voModel);
}
//Initial View
public ViewResult DataSearch(string text)
{
DataSearchModel oModel = new DataSearchModel();
oModel.alMainDDL = DLA.DataSearchContext.getMainDDL();
return View(oModel);
}
PartialView
#model ISC.Utilities.GISTransactionTools.Models.DataSearchModel
#(Html.Telerik().Grid(Model.dtResultSet1)
.Name("Grid")
.Footer(false)
.Columns(columns =>
{
columns.Bound(o => o.Row[0]).Title("T_PRCL");
}))
PartialView Grid has actually more columns, this is just to make it work.
I am not using Telerik, but here is how I am doing something similar:
In the initial view I have the following code:
#using (Ajax.BeginForm("PhoneForm", "Home", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "form-lead", InsertionMode = InsertionMode.Replace, OnSuccess = "HookupValidation" })) {
#Html.ValidationSummary(false, "Please address the following items:")
<div class="phone">
<div class="field">
#Html.LabelFor(model => model.Phone1)
#Html.EditorFor(model => model.Phone1)
#Html.ValidationMessageFor(model => model.Phone1)
</div>
<div class="button">
<input type="submit" value="Get Customer" name="submit" /></div>
</div>
}
<div id="form-lead">
</div>
Basically, when the "Get Customer" button is clicked, it will call, via AJAX, the "PhoneForm" method in my "Home" controller. This method generates the partial view which is then inserted (InsertionMode = InsertionMode.Replace) into the (UpdateTargetId = "form-lead"). The OnSuccess function is just to be sure that client side validation and jQuery events are hooked up on the partial view. If you don't do this, none of the client side validation or script will work for items in the partial view.
The controller code for "PhoneForm" is as follows:
[HttpPost]
public PartialViewResult PhoneForm(string Phone1) {
HomeViewModel viewModel = new HomeViewModel();
// ... get data and set up view model here ... //
// ... also choose which partial view you want to return ... //
return PartialView("LeadInfoPartial", viewModel);
}
Hope this helps you solve your issue.
Alright got it to work in Javascript.
View
<script type="text/javascript"> $('#btnSubmit').click(function () {
var time = new Date().getTime(); // #* unique random number to workaround IE cache issue - IE will cache the ajax if you
don't use this *#
var oMainDDL1 = $('#MainDDL1').data("tComboBox");
var oSubDDL1 = $('#SubDDL1').data("tComboBox");
var sSearch1 = $("#Search1").val();
var actionURL = '#Url.Action("getGrid1", "DataSearch", new { MainDDL1
= "PLACEHOLDER" })'.replace('PLACEHOLDER', oMainDDL1.value()) + "&SubDDL1=" + oSubDDL1.value() + "&Search1=" + sSearch1 + "&time=" +
time;
if (actionURL != null) {
$.get(actionURL, function (data) {
$('#result1').fadeOut('slow', 'linear', function () { $('#result1').empty(); $('#result1').append(data); });
$('#result1').fadeIn('slow', 'linear', function () {
if ($.browser.msie) {
this.style.removeAttribute('filter'); // #* Needed to fix IE7 cleartype bug with jQuery fade, but will crap out
on FF/Chrome *#
}
});
});
}
});
}); </script>
#(Html.Telerik().ComboBox()
.Name("MainDDL1")
.AutoFill(true)
.DataBinding(binding => binding.Ajax().Select("LoadMainDDL", "DataSearch"))
.HighlightFirstMatch(true)
.ClientEvents(events => events.OnChange("onMainDDL1Change"))
)
#(Html.Telerik().ComboBox()
.Name("SubDDL1")
.DataBinding(binding => binding.Ajax().Select("LoadSubDDL1", "DataSearch"))
.HighlightFirstMatch(true)
.ClientEvents(events => events.OnDataBinding("onSubDDL1DataBinding"))
)
#Html.TextBox("Search1")
<input type="button" class="t-button button1" value="Search"
id="btnSubmit" />
<div id="result1"> </div>
Controller
public PartialViewResult getGrid1(string MainDDL1, string SubDDL1, string Search1)
{
DataSearchModel voModel = new DataSearchModel();
voModel.dtResultSet1 = DLA.DataSearchContext.getResultSet1(MainDDL1, SubDDL1, Search1);
return PartialView(MainDDL1, voModel);
}
public ViewResult DataSearch(string text)
{
DataSearchModel oModel = new DataSearchModel();
oModel.alMainDDL = DLA.DataSearchContext.getMainDDL();
return View(oModel);
}