Reputation: 351
Dynamic JavaScript on change event not firing I have my action result as follows
public ActionResult About()
{
ViewBag.Script = "<input type='text' name='myName' onchange='nameChange(this)' /><br/>" +
"<script type='text/javascript'>function nameChange(d){" +
"$('[name=myEmail]').val('');" +
"$.ajax({type: 'POST', url: '/Home/Search', data: '{name:d}', " +
"contentType: 'application/json; charset=utf-8', dataType: 'html'," +
"success: function(data) { $('[name=myEmail]').val(data.toString()); } });" +
"}</script>"
+ "<input type='text' name='myEmail' />";
ViewBag.Message = "Your application description page.";
return View();
}
I have my controller as follows
public ContentResult Search(string name)
{
return Content("[email protected]");
}
But the action url is not getting recognized can some one help me
cshtml
@if (ViewBag.Script != null)
{
@Html.Raw(ViewBag.Script)
}
Upvotes: 0
Views: 72
Reputation: 3393
With contentType: 'application/json; charset=utf-8'
you are defining that you will send Json
with the $.ajax
request but you are not. You should make a Json
object by changing the $.ajax data
to:
data: JSON.stringify({name:d})
You have also defined a POST transaction in your $.ajax
so the Controller Action should be decorated with a [HttpPost]
attribute:-
[HttpPost]
public ContentResult Search(string name)
{
return Content("[email protected]");
}
Upvotes: 1