开发者

Invoking action method using Java script in asp.net MVC

开发者 https://www.devze.com 2023-03-11 16:38 出处:网络
I have a form, I want to check the username is availability. I that I have html textbox, in Onclcik I\'m calling java script function. The script has to call开发者_C百科 the Action methods in controll

I have a form, I want to check the username is availability. I that I have html textbox, in Onclcik I'm calling java script function. The script has to call开发者_C百科 the Action methods in controller. Based upon the username availability it has to return either 1 or 0. I have tried Json. But its is showing "Microsoft JScript runtime error: '$' is undefined". Can anyone help me in this.


If you get that message it means you're trying to use jQuery but you haven't included the library. You can use Google's CDN. I guess you've used Ajax to call. Something like this:

$.ajax({
    type: 'POST',
        url: '<%=Url.Action("Your Action", "Your Controller")%>',
    data: { userName: $('#UserName').val(), password: $('#Password').val() },
        dataType: 'json',
        complete: function(XMLHttpRequest, textStatus) {
    // User your JSON response.
    }
});

If you're using a POST you have to decorate your action with the attribute [HttpPost] and remember to specify JsonRequestBehavior.DenyGet when you return your JSON object:

[HttpPost]
public JsonResult CheckUserName(string userName, string password)
{
    // notification: your object
    return (Json(notification, JsonRequestBehavior.DenyGet));
}


If you are using Jquery (the $ sign), then that means that you need a script reference to jquery implementation before your javascript code that calls JSON.

script type="text/javascript" src="jquery.js"></script>

Where jquery.js is the latest version of the jquery javascript file

0

精彩评论

暂无评论...
验证码 换一张
取 消