ASP.NET MVC3 and jquery form plugin - c#

I'm using ASP.NET MCV3, jquery 1.5.2 and jquery form plugin.
Here's the sample code:
<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function () {
$('#uploadForm').ajaxForm({
dataType: 'json',
beforeSubmit: function () { alert('beforeSubmit'); },
success: function() { alert('success'); },
error: function () { alert('error'); }
});
});
</script>
<form id="uploadForm" action="#Url.Action("UploadFile")" method="post">
<input type="submit" value="Submit file" />
</form>
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult UploadFile()
{
return Json(new { message = "success" });
}
When I submit the form, I always get the following error message: Expected ';'
I searched SO, Google.. but couldn't find any solution to this problem.
I found Darin's comment here, but I need to have beforeSubmit and success events.
Any help would be greatly appreciated!

I changed dataType from json to text and then I parsed the result. Everything seams to work ok.
<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function () {
$('#uploadForm').ajaxForm({
dataType: 'text',
beforeSubmit: function () { alert('beforeSubmit'); },
success: processJson,
error: function () { alert('error'); }
});
});
function processJson(responseJson) {
var obj = jQuery.parseJSON(responseJson);
alert(obj.message);
}
</script>

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"
);
});

Ajax call does not work in mvc 4

I am pulling my hair. For the love of my life I cannot make this work. I have a form in my view:
<div id="cancel" class="cancel">
<form method="post" class="cancelForm">
<input type="hidden" class="cancelId" name="cancelId" value="#appliedLvl.LeavesId" />
<input id="cancelMe" class="cancelMe" type="submit" value="Cancel"/>
</form>
</div>
The javascript
$(document).ready(function () {
$(".cancelForm").submit(function () {
var MYcancelId = $('.cancelId').val();
$.ajax({
type: "POST",
url: "/Home/Cancel",
success: function (result) {
alert("ok");
},
error: function (request, status, error) {
debugger;
confirm(request);
}
});
})
});
And the Controller
[HttpPost]
public ActionResult Cancel(Guid cancelId )
{
//do stuff here
return PartialView();
}
I always get into the error function of the ajax. No matter what I have tried. This same javascript code works perfectly on my php projects. Don't know what is wrong here. Thanks in advace for any help.
Edit
The error here was the fact that I was expecting in the Action a Guid not a string!
You aren't passing in a cancelId parameter, so it isn't seeing your controller method.
$(document).ready(function () {
$(".cancelForm").submit(function () {
var MYcancelId = $('.cancelId').val();
$.ajax({
type: "POST",
url: "/Home/Cancel",
data: { cancelId = MYcancelId },
success: function (result) {
alert("ok");
},
error: function (request, status, error) {
debugger;
confirm(request);
}
});
})
});

Jquery click event not firing after getting json data

I'm working on an Asp.Net MVC3 application, using jQuery. On a specific page, the user is invited to enter the telephone number to search for a company. So, there is a result (_Result partial view) whitch I get by using json when clicking on the Search button.
On an other part, if the result is on multiple pages, when the user click the "Next button", nothing happen. Knowing that if I click on the Next button before clicking on the Search button, I have my click event fired.
The Next button is in the _Result partial view.
Here's my code HTML / Razor :
<div>
<div>
<span>Téléphone ?</span>
<input id="idTxTel" type="text" name="txTelephone"/>
<input id="idBnSearch" type="submit" value="Chercher" name="bnSearch"/>
</div>
#Html.Partial("_Result", Model)
</div>
In the _Result partial view
<div>
<span>Page N sur M</span>
<input id="bnPreviousPage" type="submit" value="Précédant" name="bnPrevious"/>
<input id="bnNextPage" type="submit" value="Suivant" name="bnNext"/>
</div>
Here's my JS code :
<script type="text/javascript">
$(document).ready(function ()
{
$("#idBnSearch").click(function ()
{
var telValue = $("#idTxTel").val();
var methodUrl = '#Url.Content("~/Search/GetReverseResult/")';
doReverseSearch(telValue, 0, methodUrl);
});
$("#bnNextPage").click(function (e)
{
alert("Next cmd");
});
});
</script>
My "doReverseSearch" method in an other JS file
function doReverseSearch(telValue, pageIdx, methodUrl)
{
$.ajax(
{
url: methodUrl,
type: 'post',
data: JSON.stringify({ Telephone: telValue, pageIndex: pageIdx }),
datatype: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('#result').replaceWith(data);
},
error: function (request, status, err) {
alert(status);
alert(err);
}
});
}
Thanks in advance
The problem is that you subscribe on the #bnNextPage click event when the document is ready but in your ajax success you replace the part of the DOM where #bnNextPage was originally.
So your click subscription is now loger active, that's way it only works if you haven't searched yet.
To make it work you need to resubscribe on the click event in the ajax success:
success: function (data) {
$('#result').replaceWith(data);
$("#bnNextPage").click(function (e)
{
alert("Next cmd");
});
},
Or as far more better solution: JQuery offers "durable" subscription with the live method. If you modify your original click code:
$("#bnNextPage").click(function (e) { alert("Next cmd"); });
to
$("#bnNextPage").live("click", function (e) { alert("Next cmd"); });
It will work without modifying your success callback.
Please note that as JQuery 1.7 the live method is deprecated and you should use the on method instead. In your case the subscription looks like the following with on:
$(document).on("click", "#bnNextPage", function (e) { alert("Next cmd"); });

Issue using JSON with JQuery and MVC

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);

Categories

Resources