0

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)
}
asked Sep 8, 2018 at 13:09
7
  • That's not Javascript. Maybe you forgot to add the Typescript tag? Commented Sep 8, 2018 at 13:13
  • No typescript jquery/javascript Commented Sep 8, 2018 at 13:15
  • The code you've shown is definitely not Javascript. Javascript has no types and no public or private or void. Commented Sep 8, 2018 at 13:17
  • I said MVC, i am binding it on the cshtml page Commented Sep 8, 2018 at 13:18
  • 1
    Why are you sending the script in this way rather than using a separate .js file? A separate file is simpler and easyer to write and debug through visual studio Commented Sep 8, 2018 at 13:26

1 Answer 1

1

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]");
}
answered Sep 8, 2018 at 15:55

2 Comments

Hi but I am not getting name as null for search function
Got it d.value gave me the expected result

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.