Populating a Webgrid from an Ajax Call - asp.net-mvc

I have a problem with populating a Webgrid from an Ajax call.
I have followed the example as showed in the following thread: mvc3 populating bind webgrid from ajax however, that did not yield any results.
When I run the website, I always get the message: "Error: undefined".
when debugging the code, I am quite sure that the problem lies in the fact that the return PartialView is the problem, as my data object in the ajax success method does not get filled with data.
Here are the examples of my code:
Ajax call:
$.fn.getCardResult = function (leerling, kaart) {
$.ajax({
type: "GET",
url: '#Url.Action("GetResults","Kaarten")',
data: { leerlingID: leerling, cardID: kaart },
cache: false,
success: function (data) {
console.log(data);
if (!data.ok) {
window.alert(' error : ' + data.message);
}
else {
$('#card').html(data);
}
}
});
}
Partial View call:
<div class="card-content" id="card">
#{
if(Model.Kaart != null && Model.Kaart.Count > 0)
{
#Html.Partial("_Kaarten")
}
else
{
#: Er zijn geen kaarten beschikbaar.
}
}
</div>
Partial View:
#model List<ProjectCarrousel.Models.KaartenModel>
#{
var grid = new WebGrid(source: Model,ajaxUpdateContainerId: "card",
defaultSort: "Topicname");
grid.GetHtml(
tableStyle: "webgrid",
columns: grid.Columns(
grid.Column("Topicname", "Topic"),
grid.Column("Taskname", "Taken"),
grid.Column("Taskpoints", "Punten"),
grid.Column("Grades", "Resultaat"),
grid.Column("Date", "Datum"),
grid.Column("Teachercode", "Paraaf Docent")
)
);
}
Controller code:
public ActionResult GetResults(int leerlingID, string cardID)
{
try
{
int Ovnumber = leerlingID;
string CardId = cardID;
List<KaartenModel> kaartlijst = new List<KaartenModel>();
IEnumerable<topic> topics = _db.topic.Include("tasks.studenttotask").Where(i => i.CardID == CardId);
foreach (topic topic in topics)
{
foreach (tasks task in topic.tasks)
{
KaartenModel ka = new KaartenModel();
ka.Topicname = task.topic.Topicname;
ka.Taskname = task.Taskname;
ka.Taskpoints = task.Taskpoints;
ka.Ranks = task.Ranks;
ka.Date = task.studenttotask.Where(i => i.Ovnumber == Ovnumber).Select(d => d.Date).SingleOrDefault();
ka.Grades = task.studenttotask.Where(i => i.Ovnumber == Ovnumber).Select(d => d.Grades).SingleOrDefault();
ka.Teachercode = task.studenttotask.Where(i => i.Ovnumber == Ovnumber).Select(d => d.Teachercode).SingleOrDefault();
kaartlijst.Add(ka);
}
}
KVM.Kaart = kaartlijst;
return PartialView("_Kaarten", KVM.Kaart);
}
catch (Exception ex)
{
return Json(new { ok = false, message = ex.Message });
}
}
If anyone could help it would be greatly appreciated.
UPDATE
After fiddling about a bit I found a solution that worked for me. Below is a snippet of an updated Ajax Call:
The solution I found was too make the Success method in another way. This made sure that the Partial View rendered properly. Below is the Ajax call snippet.
$.ajax({
url: '#Url.Action("GetAjaxCall","Home")',
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
data: { id: id },
})
.success(function (result) {
$('#sectionContents').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});

The solution I found was too make the Success method in another way. This made sure that the Partial View rendered properly. Below is the Ajax call snippet.
$.ajax({
url: '#Url.Action("GetAjaxCall","Home")',
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
data: { id: id },
})
.success(function (result) {
$('#sectionContents').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});

Related

render MVC view with json data

I have a method that return json data to my mvc view, not sure why my view shows json data instead of what I have in success part. This is my Post method:
[HttpPost]
[Route("resetpassword")]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel resetPasswordViewModel)
{
...
if (ModelState.IsValid)
{
if (resetPasswordViewModel.Password == resetPasswordViewModel.ConfirmPassword)
{
var user = Task.Run(() => Service.GetUserByEmailAsync(email)).Result;
if (user != null)
{
userRequest.Id = user.FirstOrDefault().Id;
userRequest.Password = resetPasswordViewModel.Password;
userRequest.Token = token;
await Service.UpdateUserAsync(userRequest);
}
}
else
{
return Json(new { status = "error", message = "Please enter the same value again" });
}
}
return Json(new { status = "success", message = "" });
}
This is my view that is modal:
#model Models.ResetPasswordViewModel
#if (Model != null)
{
<div class="page resetPassword">
#using (Html.BeginForm("resetpassword", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="modal" id="reset-password">
<div class="modal-content">
<span class="close">X</span>
<div><input type="email" name="email" id="email" readonly value=#Model.Email /></div>
<div class="create-user-label">Password</div>
....
and this is my ajax function:
function resetPassword() {
var postResult = null;
var data = {
Email: document.getElementById('email').value
};
var path = "/resetpassword";
var errorMessage = document.getElementById('Message');
$.ajax({
dataType: "json",
contentType: "text/plain",
url: path,
type: "POST",
cache: false,
data: data,
success: function (result) {
postResult = $.parseJSON(result);
alert(postResult.data);
if (result && result.message) {
$('#reset-password').hide();
$('#reset-thank-you').show();
}
},
error: function () { alert("error"); }
});
}
but instead of my view I only see json data in my screen like:
{"status":"success","message":""}
Your data will be automatically converted from JSON format into Javascript objects.
Presumably you just want to display the message in an alert:
success: function (result)
{
alert(result.data.message);
},
Well your data is going through, looks like you have some mapping problems, you should try this.
$.ajax({
dataType: "json",
contentType: "text/plain",
url: path,
type: "POST",
cache: false,
data: data,
success: function (result) {
alert(result['status']);
if (result['status']== 'success') {
$('#reset-password').hide();
$('#reset-thank-you').show();
}
},
error: function () { alert("error"); }
});

jquery ajax always get error section when try to pass json object(simple)

var jso = { "namep": "a", "age": "10" };
$.ajax({
type: 'POST',
url: '#Url.Action("gettestjsn","Cart")',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(jso),
success: function (data) {
alert(data.namep);
},
error: function () { alert("err"); }
});
this code always go to error function and i does not fire my mvc action,aslo i have a prop class which does match to this json obj. why is that i m new to json and jquery ajax please help
this is my action
public ActionResult gettestjsn(jso jso)
{
//do some here
return View();
}
Remove contentType from the ajax attributes and add
dataType: 'json',
This will work if the url is correct
this is how your code should look like
var jso = { "namep": "a", "age": "10" };
$.ajax({
type: 'POST',
url: '#Url.Action("gettestjsn","Cart")',
data: jso,
success: function (data) {
alert(data.namep);
},
error: function () { alert("err"); }
});
Also i would refrain from using alerts. Either use console.log or debug using the inspector in your browser (comes inbuilt with chrome) to see what your data from the server looks like.
Try like this,
var jso = { "namep": "a", "age": "10" };
$.ajax({
type: 'POST',
url: '/Cart/gettestjsn',
contentType: 'application/json; charset=utf-8',
data: jso,
success: function (data) {
alert(data.namep);
},
error: function (jqxhr, status, error) { alert("err:" + status + ':' + error); }
});
and your action should be,
[HttpPost]
public ActionResult gettestjsn(jso jso)
{
//do some here
return View();
}
Hope it helps.

Passing Multiple Checkbox value using jquery ajax

I am displaying multiple records on my ASP.NET MVC 4 view where each record has a checkbox. I want the user to be able to select multiple records (by checking checkboxes) and click Delete button in order to delete them. So far I can call the Delete Action method via jquery ajax but the problem is my action method does not seem to be accepting the passed array.
Here is my jquery code:
$(function () {
$.ajaxSetup({ cache: false });
$("#btnDelete").click(function () {
$("#ServicesForm").submit();
});
$("#ServicesForm").submit(function () {
var servicesCheckboxes = new Array();
$("input:checked").each(function () {
//console.log($(this).val()); //works fine
servicesCheckboxes.push($(this).val());
});
$.ajax({
url: this.action,
type: this.method,
data: servicesCheckboxes,
success: function (result) {
if (result.success) {
}
else {
}
}
});
return false;
});
});
and here is my action method:
[HttpPost]
public ActionResult DeleteServices(int[] deleteservice)
{
if (deleteservice != null)
{
//no hit
}
}
What am I missing?
Edit
I also tried console.log(servicesCheckboxes); before $.ajax() which outputs ["3", "4"] but still get null when I pass data as specified in answer below data: { deleteservice: servicesCheckboxes }. Even I tried data: [1,2] but still action method shows null for deleteservice in action method.
Just pass the array to your action:
$.ajax({
url: this.action,
type: this.method,
dataType: "json"
data: { deleteservice: servicesCheckboxes }, // using the parameter name
success: function (result) {
if (result.success) {
}
else {
}
}
});
Or, just use the serialize() jquery method to serialize all fields inside your form:
$.ajax({
url: this.action,
type: this.method,
dataType: "json"
data: $(this).serialize(),
success: function (result) {
if (result.success) {
}
else {
}
}
});
In your controller:
[HttpPost]
public ActionResult DeleteServices(int[] deleteservice)
{
bool deleted = false;
if (deleteservice != null)
{
// process delete
deleted = true;
}
return Json(new { success = deleted });
}
Finally got it working. "MVC detects what type of data it receive by contentType" as explained here so I made the following changes to $.ajax()
$.ajax({
url: this.action,
type: this.method,
dataType: "json"
//data: { deleteservice: servicesCheckboxes }, // using the parameter name
data: JSON.stringify({ deleteservice: servicesCheckboxes }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.success) {
}
else {
}
}
});

Ajax call to controller method not passing parameter

I am trying to make an AJax call to a controller method the parameter is null no matter what I try. I have followed all the similar SO posts but to no avail. Sorry if the answer is there, I cant find it. The code I have is...
Ajax Call
var sguid = $(nTr).attr('id');
$.ajax({
url: "/Dashboard/Reporting/GetBlacklistedSoftwareItems",
type: 'POST',
dataType: 'json',
data: JSON.stringify({guid: sguid}),
statusCode: {
404: function() {
alert("page not found");
}
},
success: function (data) {
//DO Something
},
error: function () {
alert("error");
}
});
Controller Method
public JsonResult GetBlacklistedSoftwareItems(string guid)
{
List<DeviceSoftware> ldevice = new List<DeviceSoftware>();
Guid i = Guid.Parse(guid);
ReportMethods reportingMethods = new ReportMethods();
ldevice = reportingMethods.GetNonCompliantApplicationReport(CompanyId);
DeviceSoftware ds = ldevice.Find(x => x.Device.Guid == i);
List<DeviceApplication> da = new List<DeviceApplication>();
if (ds != null)
{
da = ds.DeviceApplications;
}
return Json(da, JsonRequestBehavior.AllowGet);
}
The method is being hit its just guid is alway null. sguid does hold the data I am trying to pass.
Can someone tell me what I am missing?
Against everything I read I changed
data: JSON.stringify({guid: sguid}),
To
data: {guid: sguid},
Now working.
Fred,
You need to make GetBlacklistedSoftwareItems a post method....
try this...
[HttpPost]
public JsonResult GetBlacklistedSoftwareItems(string guid)
{
Small changes needs to be done.
var sguid = $(nTr).attr('id');
$.ajax({
url: "/Dashboard/Reporting/GetBlacklistedSoftwareItems",
contentType: "application/json; charset=utf-8" ,//This is very important
type: 'POST',
dataType: 'json',
Data: JSON. stringify ({guild: squid}),
statusCode: {
404: function() {
alert("page not found");
}
},
success: function (data) {
//DO Something
},
error: function () {
alert("error");
}
});
Add the contentType: "application/json; charset=utf-8" , to the $.Ajax Call.
:)

how do I get the form data in a javascript object so I can send it as the data parameter of an $.ajax call

How to return json after form.submit()?
<form id="NotificationForm" action="<%=Url.Action("Edit",new{Action="Edit"}) %>" method="post" enctype="multipart/form-data" onsubmit='getJsonRequestAfterSubmittingForm(this); return false;'>
<%Html.RenderPartial("IndexDetails", Model);%>
</form>
$.ajax({
url: '<%=Url.Action("Edit","Notification") %>',
type: "POST",
dataType: 'json',
data: $("#NotificationForm").submit(),
contentType: "application/json; charset=utf-8",
success: function(result) {
if (result.Result == true) {
alert("ghjghsgd");
}
},
error: function(request, status, error) {
$("#NotSelectedList").html("Error: " & request.responseText);
}
});
I guess what you're actually looking for is not the Submit method, but how to serialise the form data to a json object. To do this you have to use a helper method like here: Serialize form to JSON
Use this instead of running the submit() method, and you'll be fine.
Also, this question is a duplicate of this (even though the question text, and the title are completely misleading): Serialize form to JSON with jQuery
Posting the jQuery extender, just in case, so that it doesn't get lost :)
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
After you have this in your page, you can update your ajax call with this:
$.ajax({
url: '<%=Url.Action("Edit","Notification") %>',
type: "POST",
dataType: 'json',
data: $("#NotificationForm").serializeObject(),
contentType: "application/json; charset=utf-8",
success: function(result) {
if (result.Result == true) {
alert("ghjghsgd");
}
},
error: function(request, status, error) {
$("#NotSelectedList").html("Error: " & request.responseText);
}
});
UPD: If you want to POST the form, then get the response as a json object, and do another ajax call.. then you should look at the jquery.form plugin. you will be able to post your form using an ajax call, then get the response, and run some js when it will return.

Resources