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"); });
Related
I have a asp:Button (named as "Save") in a Web Page. It has separate code for
CommandName and CommandArgument defined in a class(.cs) file, to save records.
It also has a OnClientClick event code.
HTML:
<asp:Button ID="btnSave" runat="server" Text="Save" CommandName="Update"
OnClientClick="saveButtonClick();" CommandArgument="Save" />
Now, When I try to use OnClick event of this button, the OnClick code does
not work. I think its due to CommandName and CommandArgument or OnClientClick
code, already defined on this button but im not sure why its not working.
Since, the onClick event is not working, so I thought to write the logic of
onClick through Ajax JQuery and then I want to call this Ajax JQuery
inside pre-defined function of Javascript called onClientClick of this button.
i.e., inside saveButtonClick(); function of Javascript code
JavaScript:
<script tyep="text/javscript">
function saveButtonClick() {
//code
}
</script>
Current Ajax JQuery Code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
function saveButtonClick() {
var chk = {};
chk.requestID = $("[id*=TempGUID]").text();
alert(chk.requestID);
chk.barCode = $("[id*=txtBarcodeNumber]").val();
alert(chk.barCode);
$.ajax({
type: 'POST',
url: "IPRForm_EditCheck.aspx/CheckDuplicate",
data: '{chk: ' + JSON.stringify(chk) + '}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
var val = data.d;
alert(val);
if (val == true) {
alert("Barcode Number already exist in system database.");
}
else {
alert("Barcode Number does not exist");
}
},
error: function (data) {
alert(data.responseText);
},
});
return false;
}
</script>
Requirement is When I click on asp:Button, it triggers the onClientClick event and go to saveButtonClick() function of Javscript, inside this function it calls the Ajax JQuery. Now, in Ajax JQuery, if pointer goes to IF condition then an alert should come and page should not reload, but if it does not goto IF condition, page should reload (as previous default behavior).
I hope I made my requirement clear to you all.
Please note that I am new in asp.net and Ajax JQuery.
Thanks in advance
function saveButtonClick() {
var chk = {};
chk.requestID = $("[id*=TempGUID]").text();
alert(chk.requestID);
chk.barCode = $("[id*=txtBarcodeNumber]").val();
alert(chk.barCode);
$.ajax({
type: 'POST',
url: "IPRForm_EditCheck.aspx/CheckDuplicate",
data: '{chk: ' + JSON.stringify(chk) + '}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async:false,//here I am not allowing event to go further until it checks the barcode existance
success: function (data) {
var val = data.d;
alert(val);
if (val == true) {
alert("Barcode Number already exist in system database.");
return false;
}
else {
return true;
}
},
error: function (data) {
alert(data.responseText);
},
});
}
and update as following:
<asp:Button ID="yourid" UseSubmitBehavior="false"
OnClientClick="return saveButtonClick()"
runat="server" />
Explanation: See, you don't want to trigger the server side code unless bar-code not exists in the database. I have used method Preventing default behavior of button to prevent triggering server-side code. if bar-code doesn't exists than it will trigger the default behavior of the button.
Let me know if it doesn't works.
change your button code like this
<asp:Button ID="yourid" UseSubmitBehavior="false"
OnClientClick="return saveButtonClick()"
runat="server" />
JS code:
function saveButtonClick()
{
if(condition fails)
return false
else
return true
}
EDIT:3
updated JS code,At last I found that async calls cannot return a value, beacuse your code will not stop execution whether you have response from your service or not..please use this solution ,only if you like it..please keep in mind that this is a SYNCHRONOUS call ....
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
function saveButtonClick() {
var result = true;
var output = $.ajax({
type: 'POST',
url: "Default.aspx/SaveUser",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false
}).responseText;
var obj = jQuery.parseJSON(output);
if(obj.d) {
alert("Barcode Number already exist in system database.");
result = false;
}
else {
alert("entering database");
}
alert(result);
return result;
}
</script>
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) {
});
});
I have a javascript function and c# fanction. I need to call to the c# function from the javascript function, but I don't know how...
Can someone help me?
Thank you!
The javascript function-
<script type="text/javascript" language="javascript">
function DeleteBook(idimg) {
// idimg is a string
var userConfirm = window.confirm('Are you sure?');
if (userConfirm == true) {
control.Sess(idimg);// The line which is colling to the c# function - doesn't work
window.open('Delete.aspx');
}
else
return false;
}
</script>
The c# function-
protected void Sess(string id)
{
Session["forDelete"] = id;
}
You can create a web method
[WebMethod(EnableSession = true)]
public static Application GetApplication(int id)
{
}
and in javascript you then do something like this
$.ajax(
{
type: "POST",
url: "Applications.aspx/GetApplication",
contentType: "application/json; charset=utf-8",
data: "{'id':" + id + "}",
dataType: "json",
success: methodToDoSomethingOnSuccess,
error: function (rhq, textStatus, errorThrown) {
alert ("some went awry");
}
});
you have to create an input of type submit that invokes your C# function using the HTML and make it hidden. Then create a div tag and using javascript do this:
#CSS
.Hidden {
display:none;
}
#HTML
<input type="submit" id="SubmitTag" OnClick="C# Functin" class="Hidden" runat="server" />
//if using MVC and Razor
#using (Html.BeginForm("Action Name", "Controller Name", FormMethod.Post)) {
<input type="submit" id="SubmitTag" class="Hidden" />
}
<div id="OnDivClick"> what you want to do in here </div>
#JS
$('#OnDivClick').click(function () {
$('#SubmitTag').trigger("click");
});
Well, there are ways to do this but I believe that you're trying to save something in the Session for the Delete.aspx page to read it. The simplest solution is just post the data in:
var form = document.createElement("form");
form.setAttribute('method', 'post');
form.setAttribute('action', 'Delete.aspx');
form.setAttribute('target', '_blank');
form.innerHTML = '<input type="hidden" name="forDelete" value="' + idimg + '" />';
document.body.appendChild(form);
form.submit();
This dynamically creates a form and submits it with idimg which will open the page Delete.aspx in a new window.
All that's left to do is go to the C# part of Delete.aspx page and catch the incoming data:
string idimg = Request.Form["forDelete"];
// Do whatever with it
Session["forDelete"] = idimg; // If you still want to save it in Session
I have the Controller method below made in ASP.NET MVC 3 (C#) who returns a PartialView:
public ActionResult InsertEmail(long idPerson)
{
PersonEmailViewModel mail = new PersonEmailViewModel();
mail.email.Person_idPerson = idPerson;
return PartialView(mail);
}
The method that I need to execute on submit form is:
[HttpPost]
public ActionResult InsertNewEmail(PersonEmail mail)
{
mail.idPersonEmail = mail.Insert(mail);
return Json(mail);
}
My partialView contains this code:
#model PlatformLib_MySql.BLL.Person.PersonEmailViewModel
<form action="" id="frmNewEmail" method="post">
<div>
E-mail: #(Html.TextBoxFor(m => m.email.email))
#(Html.HiddenFor(m => m.email.Person_idPerson))
<input type="submit" value="Insert" id="btnSubmitMailInsert" />
<input type="button" value="Cancel" id="btnCancelMailInsert" />
</div>
</form>
In my JS file I run this code on #btnSubmitMailInsert button:
jQuery("#btnSubmitMailInsert").click(function () {
submitNewEmail();
window.location.reload();
});
function submitNewEmail() {
event.preventDefault();
var mail = {
email: jQuery("#frmNewEmail #email_email").val(),
Person_idPerson: jQuery("#frmNewEmail #email_Person_idPerson").val()
};
var request = jQuery.ajax({
url: '/Person/InsertNewEmail',
data: mail,
type: 'POST',
dataType: 'json',
cache: false
});
request.done(function (msg) {
console.log(msg);
});
request.fail(function (msg) {
console.log(msg);
});
}
My problem is focused on Ajax request. Rarely I can make the "happy way", where on submit click, the event is activated on jQuery, calls the method "submitNewEmail()", that calls an Ajax, executes the method on controller and pass with success. But not so... It always returns with fail, not because error returned by controller method, but simply because ajax doesn't runs properly, doesn't execute the method on controller, even with a breakpoint inserted there (on VS2010).
In this JS code posted by me here is an attempt to alternatively solve this problem, unsuccessful.
The original code is:
jQuery.ajax({
url: '/Person/InsertNewEmail',
data: mail,
type: 'POST',
dataType: 'json',
cache: false,
success: function (result) {
debugger;
jQuery("#tblEmail").append("<tr><td>Email inserido</td></tr>");
},
error: function () {
debugger;
alert("Erro ao inserir e-mail.");
}
});
I left the "console.log(msg)" temporary, just to solve this problem.
Can someone of you tell me what is happening, or to point where is my error?
I found the problem. Everything was right, but some detail damaged the code: window.location.reload();
I made some changes in my code, that looks like it:
jQuery.ajax({
url: '/Person/InsertNewEmail',
data: mail,
type: 'POST',
dataType: 'json',
cache: false
}).done(function (data) {
// Do something
});
The another way is right too, the only relevant change was:
jQuery("#btnSubmitMailInsert").click(function () {
event.preventDefault();
submitNewEmail();
// window.location.reload // -> Commented for testing and everything worked fine.
});
Thanks for trying to help me. This helped me so much.
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>