Reputation: 31
hello all I am new to mvc I want to call a method of a controller which is not an action method in a view through $.ajax but i am getting error in browser console .I want to ask that is it not possible to call a method which is not action method through ajax. code for view
@{
ViewBag.Title = "About Us";
}
<script type="text/javascript">
function ajaxcall() {
$.ajax({
url: 'ValidatePin',
type: 'Post',
success: function (result) {
alert(result.d);
}
})
}
</script>
<h2>About</h2>
<p>
Put content here.
<input type="button" onclick="ajaxcall()" value="clickme" />
</p>
here is my code for method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Services;
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
[WebMethod]
public static string ValidatePin()
{
return "returned from controller class";
}
}
}
Upvotes: 0
Views: 854
Reputation: 231
Alternative solution with incoding framework:
Controller
[HttpGet]
public ActionResult ValidatePin()
{
return IncJson(new AlertVM(){Message = "Some thing"});
}
Razor page
@(Html
.When(JqueryBind.Click)
.Do()
.AjaxGet(Url.Action("ValidatePin","Pin"))
.OnSuccess(dsl => dsl.Utilities.Window.Alert(Selector.Incoding.Data<AlertVM>(r=>r.Message)))
.AsHtmlAttributes()
.ToButton("clickme"))
Upvotes: 1
Reputation: 872
why do you insist not to implement an action method instead of this static method? my second question is what your method actully does? validation something? so how do you pass it to this method?
Think you might want something like this:
public JsonResult ValidatePin(string id) /*id=pin*/
{
bool result;
// do something
return Json(new { IsValid = result, Message = "something" }, JsonRequestBehavior.AllowGet);
}
$.ajax({
url: '/validatepin/' + pin,
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.message + ' ' + data.IsValid);
}
})
Upvotes: 0