Javascript link with onClick event - c#

I am using a third-party shopping cart from http://simplecartjs.com/ .
For a normal checkout I can use:
<a href="javascript:;" class="simpleCart_checkout" >Checkout</a>
And it works. But I need to add some server-side functionality and don't know how to go about this. The code inside the javascript file where the simpleCart_Checkout class is stored is as follows:
me.addEventToArray( getElementsByClassName('simpleCart_checkout') , simpleCart.checkout , "click");
EDIT: and this:
me.checkout = function() {
if( me.quantity === 0 ){
error("Cart is empty");
return;
}
switch( me.checkoutTo ){
case PayPal:
me.paypalCheckout();
break;
case GoogleCheckout:
me.googleCheckout();
break;
case Email:
me.emailCheckout();
break;
default:
me.customCheckout();
break;
}
};
So I tried doing it using a button calling the method directly:
<asp:Button ID="CheckoutButton" runat="server" Text="Checkout"
onclick="CheckoutButton_Click" OnClientClick="Checkout()" />
<script type="text/javascript">
function Checkout() {
javascript: simpleCart.checkout;
}
</script>
Which calls the server-side but doesn't call the javascript link. I am new to asp.net and javascript so don't really know any other ways of how I can do this, please help.

try this:
<asp:Button ID="CheckoutButton" runat="server" Text="Checkout"
onclick="CheckoutButton_Click" OnClientClick="javascript:Checkout();" />
<script type="text/javascript">
function Checkout() {
simpleCart.checkout();
return true;
}
</script>
Edit:
you want your scripts being called after the server event. then you'll need to call your Checkout function at the end of "CheckoutButton_Click".
Page.ClientScript.RegisterStartupScript(Page.GetType(), "calling checkout", "<script>CheckOut();</script>", true);
simpleCart.checkout() doesn't got a chance to do redirect, as OnClientClick returns true and post back happens.

That should be enough.
function Checkout() {
simpleCart.checkout();
return true;
}

You can call your javascript from Server side.
Page.RegisterStartupScript will assists you to fire javascript from code behind.
Page.ClientScript.RegisterStartupScript(Page.GetType(), Guid.NewGuid().ToString(), "alert('hello')", true);

Related

cannot get the session on vb page when it set using jquery

I have a img button. When it is clicked, I set the session value using jquery. however I cannot get the session on vb code behind. My process is like that after the user click the image, I set the session. When the user open popup page and return the page. I need to check the session to do something. However in the vb code, the session is nothing. Would some one tell me how to do it.
The below code call the function:
<asp:Image ID="img" runat="server" onclick="SetSession(hdID);" ImageUrl="pic_bottle.gif" />
The jquery script:
function SetSession(hdID) {
var hd = $('#' + hdID);
var hdValue = hd.val();
if (hdValue == "s") {
$.session.set('UpdateProdOrder', -1);
}
else {
var hdProdID = $('#hdProdID').val();
$.session.set("UpdateProdOrder", hdProdID);
}
alert($.session.get("UpdateProdOrder"));
}
The vb code behind never get the session
If Not Session("UpdateProdOrder") Is Nothing Then
'do something
updateOrder()
end if
The localStorage and sessionStorage properties allow saving key/value pairs in a web browser.
The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed).
These values are maintained on the client side, but you are trying to retrieve it on the server side. session variables are server side
Solution:
Method 1:
You'd have to have a little ajax call to talk to the server to set it.
please check it out
Method 2 :
Assigning the ASP.NET Session Variable using Javascript.
<script type="text/javascript">
function SetSession(hdID)
{
var hd = $('#' + hdID);
var hdValue = hd.val();
if (hdValue == "s") {
'<%Session["UpdateProdOrder"] = "' + -1+ '"; %>';
}
else {
var hdProdID = $('#hdProdID').val();
'<%Session["UpdateProdOrder"] = "' + hdProdID+ '"; %>';
}
alert('<%=Session["UpdateProdOrder"] %>');
}
</script>
Accessing ASP.NET Session variable using Javascript:
<script type="text/javascript">
function GetSession()
{
var updateProdOrder= '<%= Session["UpdateProdOrder"] %>';
alert(updateProdOrder);
}
</script>
You cannot change a server side Session object with javascript directly. You need to send it to the server somehow. This can be done by changing the image to an ImageButton and do a PostBack to modify the Session object. But since you seem to have some data in hdID. You cannot send that to the server with a ImageButton alone, you'll need a HiddenField
<asp:ImageButton ID="ImageButton1" runat="server" OnClientClick="SetSession(hdID);"
ImageUrl="pic_bottle.gif" OnClick="ImageButton1_Click" />
<asp:HiddenField ID="HiddenField1" runat="server" />
<script type="text/javascript">
var hdID = 'test';
function SetSession(hdID) {
$('#<%= HiddenField1.ClientID %>').val(hdID);
}
</script>
And then in code behind
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Session["UpdateProdOrder"] = HiddenField1.Value;
Label1.Text = string.Format("Session value is now '{0}'", Session["UpdateProdOrder"]);
}
You could do this also without the javascript SetSession, but that depends on where and when hdID is used on other parts of the page.

MVC ActionLink calling multiple JQuery functions

I'm trying to call a confirm, then an alert function from an MVC action link and I'm stuck. The code is as follows:
My view has the following actionlink:
#Html.ActionLink("JQuery Testing", "BuildProject", Model, new { onclick = " return ConfirmProjectSubmit()" })
which calls the controller to save a project to the database. I'm trying to throw a confirm statement onClick. Once that action is performed, the following action is called:
return RedirectToAction("ProjectDetails", "Project", new RouteValueDictionary(new { id = currentProject.Id, msg = message }));
to alert the user that the project was actually created.
and then at the bottom of my view:
#section scripts {
<script type="text/javascript">
function ConfirmWorkflowSubmit() {
$.confirm({
title: 'Confirm!',
content: 'Simple confirm!',
buttons: {
confirm: function () {
},
cancel: function () {
}
}
});
return false;
};
</script>
#if (ViewBag.message != null)
{
<script type="text/javascript">
$(document).ready(function () {
$.alert({
title: 'Workflow successfully created',
content: '#ViewBag.message',
type: 'green',
});
});
</script>
}
}
both of the actions are firing, but incorrectly. I'm newer to MVC and moreso to Jquery. Basically I need to figure out how to not have it submit if the user doesn't confirm, and then make sure the message only pops on the way back. I think I just need help ordering what I have properly.
Thanks in advance.
EDIT. Okay, so I see part of the problem. It's not the $confirm function that's actually submitting the form, it's the button action clicked once the dialog is open. I'm really stuck here, and this has to be easier than I'm making it. Help!
I'm not saying you can't do it the way you have, but this is normally how I set up my bindings:
$(document).ready(function ()
{
// add the e here -- it is the event which initiated the binding
$(".buildButton").on("click", function (e)
{
if (ConfirmProjectSubmit())
{
alert('confirm');
}
else
{
// e.preventDefault() cancels the click action
e.preventDefault();
alert('cancel');
}
});
});
function ConfirmProjectSubmit()
{
// some confirm logic
// return true for confirmed, false for cancelled
return false;
}
Remove the onclick in your action. There is no need to have a jQuery binding and an onClick.
This is sort of an outline, you can add your logic in various places to finish it out.

How to execute jQuery in MVC Controller C#

Is it possible to run jQuery from a MVC C# controller?
if (ModelState.IsValid){
//lots of C# asp.net code here
jqueryFunctionName();
}
It's important that there is a check somehow before the jQuery runs
Perhaps i can do it straight from jQuery itself, but i'm not sure how to check it?
The idea is Form -> Submit -> SOMETHING checks if valid -> if yes then wait graphic -> 2 seconds pauze -> redirect to "thanks.cshtml"
In your controller's action:
var vm = new YourViewModelTypeWithPropertyIsValid();
vm.IsValid = ModelState.IsValid;
return View(vm);
In your view:
#model YourViewModelTypeWithPropertyIsValid
<script type="text/javascript">
var isModelValid = #Model.IsValid ? 'true' : 'false';
$( document ).ready(function() {
// Any JS code here
// ...
if (isModelValid) {
setTimeout(
function () {
location.assign('/redirect_path_after_2s_delay');
},
2000);
);
}
});
<script>
I prefer typed views.
If you use untyped views, use the code below.
In your controller's action:
ViewData["IsModelValid"] = ModelState.IsValid ? "true" : "false";
return View();
In your view:
<script type="text/javascript">
var isModelValid = #ViewData["IsModelValid"];
$( document ).ready(function() {
// Any JS code here
// ...
if (isModelValid) {
// See the code above.
}
});
<script>
If the code runs in the view then you can try something like this.
is a special asp tag.
If the should indeed run in controller, than it is not possible to run JS code there.
if (ModelState.IsValid){
//lots of C# asp.net code here
<text>
<script>
jqueryFunctionName();
</script>
</text>
}

OnClientClick isn't firing for ImageButton

I have an ASP.NET ImageButton that OnClientClick() is supposed to fire a js function that reads the values from a two text fields, send it to a server-side WebMethod. With the WebMethod sending it to another entity method which handles the storage. I've tried debugging by setting breakpoints in the WebMethod and storage method on the serverside but neither is getting reached. I then tried setting a breakpoint on client-side using the Mozilla Firebug tool. The js function never gets called and the page just refreshes. I set a breakpoint in another js function and it was traced perfectly. Any help?
ASP
<asp:ImageButton input="image" ID="btnSend" ImageUrl="Images/send_button.jpg"
runat="server"
onclientclick="javascript:handle(); return false">
</asp:ImageButton>
JS
function handle() {
window.$get("#" + "<%= btnSend.ClientID %>").click(
function () {
var txtVC = window.$get("#" + "<%= txtVC.ClientID %>").value();
var txtMsg = window.$get("#" + "<%= tbMgSend.ClientID %>").value();
if (txtVC != "" || txtMsg != "") {
window.PageMethods.SendMsg(txtVC, txtMsg, txtMessageResult);
return window.$get("#" + "<%= lblMessageStatus.ClientID%>").value("SUCCESS"),
alert("SUCCESS");
}
else {
return alert("Text Message is Empty!");
}
});
}
function txtMsgResult(result) {
if (result != '') {
window.$("#" + "<%= lblMessageStatus.ClientID %>").innerHTML = result;
alert("SUCCESS");
}
}
I've tried the following:
* OnclientClick with and without return
* $get with and without concat(+)
* changing the server-side to a method instead of web method and that also didn't fire
Have you tried it without the return false?
<asp:ImageButton input="image" ID="btnSend" ImageUrl="Images/send_button.jpg"
runat="server"
onclientclick="handle()">
</asp:ImageButton>
Maybe it doesn't work because it autoPostBack.
I'm not sure there is a way to turn it off in an ImageButton. Why not use a HTML control instead ?

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

I want to redirect from one page to another page in ASP.NET MVC 3.0 using JavaScript/jQuery/Ajax. On button click event I have written JavaScript code like below.
function foo(id)
{
$.post('/Branch/Details/' + id);
}
My controller code is like this:
public ViewResult Details(Guid id)
{
Branch branch = db.Branches.Single(b => b.Id == id);
return View(branch);
}
When I click on a button it is calling the Details action inside BranchController, but it doesn't return to the Details view.
I didn't get any error or exception. It's showing status 200 OK in Firebug. What is wrong in my code and how can I redirect to the Details view page?
You are not subscribing to any success callback in your $.post AJAX call. Meaning that the request is executed, but you do nothing with the results. If you want to do something useful with the results, try:
$.post('/Branch/Details/' + id, function(result) {
// Do something with the result like for example inject it into
// some placeholder and update the DOM.
// This obviously assumes that your controller action returns
// a partial view otherwise you will break your markup
});
On the other hand if you want to redirect, you absolutely do not need AJAX. You use AJAX only when you want to stay on the same page and update only a portion of it.
So if you only wanted to redirect the browser:
function foo(id) {
window.location.href = '/Branch/Details/' + id;
}
As a side note:
You should never be hardcoding urls like this. You should always be using url helpers when dealing with urls in an ASP.NET MVC application. So:
function foo(id) {
var url = '#Url.Action("Details", "Branch", new { id = "__id__" })';
window.location.href = url.replace('__id__', id);
}
This could be done by using a hidden variable in the view and then using that variable to post from the JavaScript code.
Here is my code in the view
#Html.Hidden("RedirectTo", Url.Action("ActionName", "ControllerName"));
Now you can use this in the JavaScript file as:
var url = $("#RedirectTo").val();
location.href = url;
It worked like a charm fro me. I hope it helps you too.
You can use:
window.location.href = '/Branch/Details/' + id;
But your Ajax code is incomplete without success or error functions.
// in the HTML code I used some razor
#Html.Hidden("RedirectTo", Url.Action("Action", "Controller"));
// now down in the script I do this
<script type="text/javascript">
var url = $("#RedirectTo").val();
$(document).ready(function () {
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Controller/Action',
success: function (result) {
if (result.UserFriendlyErrMsg === 'Some Message') {
// display a prompt
alert("Message: " + result.UserFriendlyErrMsg);
// redirect us to the new page
location.href = url;
}
$('#friendlyMsg').html(result.UserFriendlyErrMsg);
}
});
</script>
<script type="text/javascript">
function lnkLogout_Confirm()
{
var bResponse = confirm('Are you sure you want to exit?');
if (bResponse === true) {
////console.log("lnkLogout_Confirm clciked.");
var url = '#Url.Action("Login", "Login")';
window.location.href = url;
}
return bResponse;
}
</script>
check the code below this will be helpful for you:
<script type="text/javascript">
window.opener.location.href = '#Url.Action("Action", "EventstController")', window.close();
</script>

Categories