I am using ASP.NET 3.5.
In my code behind i have this code that i want to execute from my JavaScript.
Private Sub CreateName()
Dim Name as String
Name = txtName.text
End Sub
And this is my JavaScript Function
<script type="text/javascript">
function doSomething() {
document.elqFormName.action = 'http://now.eloqua.com/e/f2.aspx'
document.elqFormName.submit();
}
</script>
So what must I place inside my JavaScript function to execute my function in my code behind?
Thanks in advance!!
I'm not sure how VB works, but it's similar to C#. I've previously done this by making a WebMethod and using ajax.
Although you could do this using WebMethods as Jimmeh stated, another option would be to use a HTML generic handler. In this approach, your CreateName method wouldn't be in a ASPX page but in a ASHX page.
Check:
http://www.aspcode.net/Creating-an-ASHX-handler-in-ASPNET.aspx
Inside your doSomething method in the javascript part you'd need to call the ASHX using Ajax.
Check:
http://docs.jquery.com/Ajax
I had this same issue, and I found the easiest way to handle it was with an AJAX call. In your ASPX page (javascript):
//======================================
/* This function creates a new instance of an XMLHttpRequest object,
based on the users browser, and returns it */
//======================================
var xmlhttp
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
//======================================
/* This function issues a request and specifies which function should handle the ajax response */
//======================================
function doSomething()
{
xmlhttp = GetXmlHttpObject();
xmlhttp.onreadystatechange=stateChanged;
var url = "CreateName.aspx"
xmlhttp.open("GET", url, false);
xmlhttp.send(null);
}
//======================================
/* This function handles the ajax response text, places it in a label */
//======================================
function stateChanged()
{
if (xmlhttp.readyState==4)
{
var returned = xmlhttp.responseText;
document.getElementById("lbl_returnStatus").innerHTML = returned;
}
}
And then in the file CreateName.aspx:
<%
'Here is where you can do anything on the server side
Dim Name as String
Name = txtName.text
'This is what will be passed back and handled by the stateChanged function
Response.Write("Success!")
%>
You can also pass parameters through an AJAX call if you need to. Since the type of request we are making is a GET, you can just add the parameters to the URL in Javascript and access them server side with the Request.Querystring("paramName") function.
I wrote a more detailed post on starting AJAX on my blog, here, if you'd like to read that as well. Cheers!
Related
I'm currently writing a MVC C# application. Everything works just fine. I have a bit of functionality, where I fill up a Bootstrap modal box using an Ajax call, but the new page gets cached, despite my efforts to prevent that.
On my main page I have the following actionhandler to fill up the modal box:
function setExtraPermsOrAtts(appID){
$.ajax({
cache:false,
url: "/Group/_modifyAppPermissionsOfGroup?appID=" + appID
}).done(function (result) {
$("#addApplicationBody").html(result);
$('#modal-add-application').modal('show');
});
}
This gets caught by the following method:
public ActionResult _modifyAppPermissionsOfGroup(int? appID = 0)
{
if (appID != 0)
{
ViewBag.selectedAppID = appID;
Session["selectedGroupAppID"] = appID;
ViewBag.modifyPermsLater = true;
}
Group group = (Group)Session["currentGroup"];
return View(group);
}
Another thing that might be relevant is the point where it 'goes wrong'. The resulting View in the Modalbox, has a few radio buttons, depending on the content of the database. There I do a razor statement to get the DB value:
bool valueOfRadButtons = BusinessLogic.Domain.GroupIS.getExistingGroupPermission(
Model.LoginGroupID, myItem.ApplicationPermissionID).LoginPermissionState;
Does anyone know where I'm going wrong? Is it the Ajax call? The ActionResult method in the Controller? Or the inline razor statement? I know the data gets saved properly, cause I see so in the DB
You can specify that the response shouldn't be cached like this:
Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
It can be more easy if you make your own attribute and decorate the action with it as shown here.
I have a mvc project, what I want to do is this:
I am sending an ajax request from my JS script. After processing it I want to redirect to a page with a model.
Now I tried sending a form as the ajax response and submit it like so:
sb.Append("<html>");
sb.AppendFormat(#"<body onload='document.forms[""form""].submit()'>");
sb.AppendFormat("<form name='form' action='{0}' method='post'>", "url..");
sb.AppendFormat("<input type='hidden' name='result' value='{0}'>", val1);
.....
And on the JS:
success: function (result) {
var form = $(result);
$(form).submit();
}
But this way i need to specify each post param, I want to send the entire model object.
How can I do that?
Edit
Full steps:
1.Using an MVC APP.
2.I submit button in my view which redirects the user to my JS code.
3.Js code sends an Ajax request to a MVC page called 'Transaction'.
4.C# code doing some actions and now I need to redirect the usr to a page named EOF with ALOT of post params, thats why I want to pass it as a ViewModel.
As you are using ajax, you could return the URL from your action and have it redirected in javascript:
Controller
public ActionResult Transaction()
{
// Do stuff
return Json(new { success = true, redirecturl = Url.Action("RedirectedAction") });
}
Then add something like this to your success handler in javascript:
Javascript (within your success handler)
success: function (result) {
if (result.success == true)
{
window.location = result.redirecturl;
}
}
You can try this:
public ActionResult YourMethod(string param)
{
//what ever you want to do with reference no
return View("EOF");
// or, if you want to supply a model to EOF:
// return View("EOF", myModel);
}
I've been trying to achieve the following:
Call my action (which returns json):
#{ var response = Html.Action("Login", "Auth"); }
And assign my json response to a global javascript variable:
<script type="text/javascript">
var response = #response;
user = response.details;
</script>
However I can't seem to get this to work the way I need it to. The response is not assigned appropriately. Is there an action call which returns json? I know I could use ajax for this, but that's not a valid option since i have to set the global variable before the document.ready is called.
Any tips appreciated...
Kind regards
You can use JavaScriptResult directly. See MSDN Doc
public JavaScriptResult Example()
{
return new JavaScript("var response = 10");
}
Useful liks related to
How to use Asp.net mvc JavaScriptResult practically
Working example for JavaScriptResult in asp.net mvc
Beware of ASP.NET MVC JavaScriptResult
But I would suggest you to Use $.getJSON() or $.Ajax() instead
Use $.getJSON(), $.post(), $.Ajax() instead, if you want JSON response back
Instead of trying to use Html.Action like a method call, use Html.RenderAction and use that action to dump any necessary JavaScript to your page. e.g.
AuthController.cs
public class Auth : Controller
{
/* snip */
[ChildActionOnly]
public ActionResult Login()
{
return View(/* model? */);
}
}
~/Views/Auth/Login.cs
<script>
var auth = #whateverinformation;
</script>
Original View
#{ Html.RenderAction("Login", "Auth"); }
<script>
user = auth.details;
</script>
Now /Auth/Login can be placed on any page and the content is included at a server level (instead of supplementary with AJAX)
And if that doesn't do it for you, think about making an HTML helper that displays the information instead of trying to use a controller action like a normal method. Something like:
public static IHtmlString Auth_Login(Htmlhelper htmlhelper)
{
String response;
/* assign response */
return new HtmlString(response); /* or maybe MvcHtmlString */
}
Implemented:
<script>
var response = #Html.Auth_Login();
user = response.details;
</script>
You may check the Channel9 discussion on Evolving Practices in Using jQuery and Ajax in ASPNET MVC Applications.
You may also check the SO question on asp.net MVC3 and jquery AJAX tutorial
You should use quotes
<script type="text/javascript">
var response = "#response";
...
How can i check in for a value in DB on blur event through jQuery.
I want to display a message if value exist in Data base.
I am using Asp.Net with csharp.
you can call C# function from your jQuery function like --
var isExist = <%=GetValueFromDB()%>;
GetValueFromDB in the codebehind should return a string result and you can check it in your jQuery. I hope this helps.
public string GetValueFromDB()
{
if(value is there)
return "your result";
return "emptystring";
}
Jquery runs on client, so you need to go to the server.
Ajax that calls a WebMethod might work for you
Do a webmethod and then do something along
$('#myInput').onblur(function()
{
$.get('myurl.aspx', {method : 'checkValue', mvalue : $(this).val()},function(data)
{
//handle your response
});
});
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>