Issue using JSON with JQuery and MVC - c#

I'm trying to execute my controller from javascript using jquery... here is my jquery code that is executing..
<script type="text/javascript">
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: $(this).serialize(),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(msg) {
var obj = msg.deserialize();
alert(msg);
}
});
});
</script>
Now it does execute my action..
Here is a sample of my controller class it is executing..
[AcceptVerbs(HttpVerbs.Post)]
[Url("Account/LogOn")]
public virtual ActionResult LogOn(string Username, string Password) {
if (Username == "test") {
return Json(new {
Success = true
});
} else {
return Json(new {
Success = false
});
}
}
Problem is.. when I run the method.. it just tries to download a "Logon" file which contains the result.. how do I put it back to an object in jquery so i can handle it the correct way, I've tried adding the success tag and attempt to check the msg but it doesnt even run it

Put your script inside document.ready before attempting to register any event handlers as the DOM might have not loaded yet:
<script type="text/javascript">
$(function() {
// ... copy - paste your script here
});
</script>
Also you don't need to set the dataType, jQuery knows it from the Content-Type response header from the server. Another remark: the msg object passed to the success handler is already a JSON object: you don't need to parse/deserialize it:
<script type="text/javascript">
$(function() {
$('form').submit(function() {
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(msg) {
alert(msg.Success);
}
});
return false;
}
});
</script>
And the solution I would recommend you is to use the jquery.form plugin. Thanks to it your js code will look as easy as:
<script type="text/javascript">
$(function() {
$('form').ajaxForm(function(msg) {
alert(msg.Success);
});
});
</script>
Very neat stuff. You don't need to bother about serializing/deserializing data, preventing default events, it can even handle file uploads.

HIDDENHANCEMENT
var obj = msg.deserialize();
If that is not a joke, you would have spotted a hidden feature :)
If you're using jQuery v.1.4.x you don't need to parse a JSON string manually.
Using an older version, try
var obj = window.JSON.parse(msg);

Related

Using Response.Redirect in the View mvc4

I am going following steps:
in the controller action no.1 redirect to view no1;
in view no.1 I want to display cshtml page and next I want to redirect to the new action no.2 by using
#{Response.Redirect(Url.Action("CreatePdf", "Home");}
directive;
Action no.2 is reached and I've got my result (pdf file) but I can;t see the view no.1 from which I've called this action.
How can I load this view and display html page?
Just a little tweak to #DavidG's answer:
<script type="text/javascript">
$(document).ready(function () {
setTimeout(DownloadPdf, 1000);
});
function DownloadPdf() {
location.href = "#Url.Action("CreatePdf", "Home")";
}
</script>
Just tested and working. It will download the file after 1sec
A redirect causes the entire session to be directed to the new page ans loses anything you have sent out. I would use jQuery instead:
<script type="text/javascript">
$(document).ready(function () {
setTimeout(DownloadPdf, 1000);
});
function DownloadPdf() {
window.location = "#Url.Action("CreatePdf", "Home")";
}
</script>
I would suggest :
public ActionResult ControllerAction1()
{
return View();
}
For the View(), for document.ready function :
$(document).ready(function () {
$.ajax({
url: '#Url.Action("Action2", "Controller")',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'html',
data: JSON.stringify(model)
})
.success(function(result) {
// return true or false
// html of json result
})
.error(function(xhr, status) {
});
});

How to add ajax loader before it loads the data in jQuery jTable?

I am using a jQuery jTable and it gives the message first "No Data Available" before it loads the data and displays a long list of it. So is it possible to display an Ajax loader (loading.gif) first while it's loading the data in the background?
Edit #Rex: i Tried this but don't know how to implement it with the jQuery jTable success function.
This is the code I tried:
$(document).on('click', '#PlayStatisticone', function (e) {
function loadingAjax(div_id) {
var divIdHtml = $("#"+div_id).html();
$.ajax({
url: '#Url.Action("_TopPlayedTracksPermissionCheck", "ReportStatistic")',
type: 'POST',
beforeSend: function() {
$("#loading-image").show();
},
success: function (data) {
$("#"+div_id).html(divIdHtml + msg);
$("#loading-image").hide();
$(function () {
$("#PartialViewTopPlayedTracks").load('#Url.Action("_PartialViewTopPlayedTracks", "ReportStatistic")');
});
},
error: function (xhr, textStatus, exceptionThrown) {
var json = $.parseJSON(xhr.responseText);
if (json.Authenticated) {
window.location.href = '/UnAuthorizedUser/UnAuthorizedUser';
}
else {
window.location.href = '/UnAuthenticatedUser/UnAuthenticatedUser';
}
}
});
Any suggestion would be really helpful
Thanks in advance.
It worked just as I wanted... I found it from an another forum
I don't know if it's ok to post worked answers from another forum or not in here:
here's the code that worked:
$(document).ready(function () {
// DOM is ready now
$.post("<%= Url.Action("ActionThatGetsTableOnly") %>",
"",
function(data) { $("#elementToReplaceId").html(); },
"html"
);
});

How to get the data from json to MVC4 c#?

I have a MVC4 single page website with a form. The loading of the contents is achieve with ajax. I do not know how to get the data out from JSON in C#? Here is my code:
JavaScript:
$("#subnt").click(function (event) {
event.preventDefault();
var url = "/Home/Submit";
$.post(url, $('form[name="cnt_us-frm"]').serialize(), function (data) {
if (data.Success === true) {
$("#min-content").hide().load("/Home/PartialSubmit").fadeIn('normal'); // loads the page into 'min-content' section
}
else {
// display error message
}
})
});
});
C#:
[HttpPost]
public JsonResult Submit()
{
return Json(new { Success = true, SomeOtherData = "testing" });
}
Please check below working code -
I have used exactly your working code -
[HttpPost]
public JsonResult Submit()
{
return Json(new { Success = true, SomeOtherData = "testing" });
}
Then I used following JQuery to hit the above action -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$('#click').click(function (e) {
$.ajax({
url: "#Url.Action("Submit")",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response);
},
success: function (data) {
if (data.Success == true)
alert(data.SomeOtherData);
}
});
});
});
</script>
<input type="submit" value="click" id="click" />
And as the output I was able to get an alert as shown below -
Easiest thing to do is use the superior json.net
[HttpPost]
public string Submit()
{
var result = new { success = true, someOtherDate = "testing"};
var json = JsonConvert.SerializeObject(result);
return json;
}
Your code is ok bu you can add debugger.and open developer tools check your data .
$.post(url, $('form[name="cnt_us-frm"]').serialize(), function (data) {
debugger;
if (data.Success === true) {
$("#min-content").hide().load("/Home/PartialSubmit").fadeIn('normal'); // loads the page into 'min-content' section
}
else {
// display error message
}
No, the other way around. How to retrieve the data from the form (json).

Making an Ajax call to a partial view after ajax success

I have a partial view that contains all my buttons and it needs to display updated values after a form is submitted. At the submission I already have it rendering another partial view, is there a way to make it work where on success of that one being rendered it re-renders. Here is the code I am trying to get to work now based on what I've seen in other places.
jQuery in my view:
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$('#ChangeGrade').click(function (e) {
var tdata = $('#form1').serialize();
var origname = $('#HeatGradeDiv').find('input[name="grade"]').first().val();
var newname = $('#HeatGradeDiv').find('input[name="updatedGrade"]').first().val();
var heatname = $('#HeatGradeDiv').find('input[name="hiddenHeat"]').first().val();
$.ajax({
type: "POST",
data: {
mCollection: tdata,
grade: origname,
updatedGrade: newname,
hiddenHeat: heatname
},
url: '#Url.Action("ChangeGrade","Home")',
success: function (result) { success(result); }
});
});
function success(result) {
$('#HeatGradeDiv').dialog('close');
$("#Partial_Chem_Analysis").html(result);
//ajax call I'm trying to get working
$.ajax({
type: "POST",
url: "/Home/ButtonsPartial",
success: function (result2) { $("#ButtonsPartial").html(result2); }
});
}
});
</script>
Here is the controller method I'm calling. When I run it now it is not getting hit.
public ActionResult ButtonsPartial()
{
ButtonsModel B = new ButtonsModel();
B.GetData(searchQ);
return PartialView(B);
}
Any help is appreciated.
If you attach it to a debugger such as (chrome developer tools or firebug) are you seeing any http or js errors?
It looks like you might need to make it a GET rather than POST...
$.ajax({
type: "GET",
url: "/Home/ButtonsPartial",
success: function (result2) { $("#ButtonsPartial").html(result2); }
});

Calling action from jquery correctly?

I've never used ajax and I'm just try to see if this will call the method from my controller and give me the desired result. The javascript debugger in VS doesn't seem to be working at the moment. Does this look right?
$("form").submit(function() {
var hasCurrentJob = $.ajax({
url: 'Application/HasJobInProgess/#Model.ClientId'
});
});
controller method
public Boolean HasJobInProgress(int clientId)
{
return _proxy.GetJobInProgress(clientId).Equals(0);
}
Update
$("#saveButton").click(function() {
var hasCurrentJob = false;
$.ajax({
url: '#Url.Action("HasJobInProgress","ClientChoices")/',
data: { id: #Model.ClientId },
success: function(data){
hasCurrentJob = data;
}
});
if (hasCurrentJob) {
alert("The current clients has a job in progress. No changes can be saved until current job completes");
}
});
Try to use the Url.Action HTML Helper method when calling an action method. This will get you the correct url to the action method. You dont need to worry about how many ../ to add/
$(function(){
$("form").submit(function() {
$.ajax({
url: '#Url.Action("HasJobInProgess","Application")',
data: {clientId: '#Model.ClientId'},
success: function(data) {
//you have your result from action method here in data variable. do whatever you want with that.
alert(data);
}
});
});
});

Categories

Resources