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
});
});
Related
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";
...
Is there such a thing as listBox1_SelectedIndexChanged but in PHP ?
Nope, but you could use jQuery :)
$(document).ready(function() {
$("#selectList").change(function() {
var myVal = $(this).val();
alert(myVal);
});
});
If you need to send data to server and get back from it, use $.post() / $ajax() etc ...
I've encountered this problem all of a sudden doing a simple ajax submit of a form. The JSON comes back formatted correctly but the browser prompts to download it. Fiddler shows the content-type as correct:
application/json; charset: utf-8
Here's my javascript:
$("#submitbutton").click(function(e) {
$.post('FormTest', function(o) {
FormCallback(o);
});
});
Here is the server side:
public JsonResult FormTest(string test) {
return Json("This worked!");
}
Again, I get back an object from the server fine, but it either prompts me to download (Firefox) or simply shows the object in a new tab in the browser (Chrome).
I found one other question like this but the author didn't explain what was wrong. This is crazy! Any ideas?
Edit: The correct code is below, beside the e.preventDefault, I also needed to tell it which form data to use:
$("#submit-button").click(function(e) {
$.post('address', $("#form").serialize(), function(o) {
FormCallback(o);
});
e.preventDefault();
});
You want to cancel the default action, I expect:
$("#submitbutton").click(function(e) {
$.post('FormTest', function(o) {
FormCallback(o);
});
return false; // <<=====
});
You can also try:
e.preventDefault();
if that doesn't work by itself
In addition to #Marc's answer I would like to add that:
return Json("This worked!");
in fact doesn't work as it doesn't return a valid JSON object. It simply returns "This worked!" to the client. You need to construct the object:
return Json(new { Message = "This worked!" });
MVC 2 returns JSON mimetype by default. If you want to receive JSON data in plain HTML you should pass your JSON data as following:
return Json(model, "text/html", JsonRequestBehavior.AllowGet);
Another point, you can mark your Action with [ChildActionOnly] and call your action in your view this way
var json = <%= Html.Action("YourActionMethod", "YourControllerName") %>
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!