1

I am trying to call a controller via ajax without to much luck. I have create this in my view

 <input type="submit" id="preview-email" value="Preview Email" /> <script type="text/javascript"> $("#preview-email").click(function () { var p = { "email": "1223" }; $.ajax({ url: '/BusinessController/PreviewEmail', type: "POST", data: p, dataType: "json", contentType: "application/json; charset=utf-8", success: function (data) { alert(data); }, error: function () { alert("error"); } }); }); </script> 

My controller

 [HttpPost] public ActionResult PreviewEmail(string email) { // string d = ViewData["editor"].ToString(); string e = System.Web.HttpUtility.HtmlDecode(email); EmailModel model = new EmailModel() { EmailBody = e }; return PartialView("_PreviewEmail", model); } 

Turning on fiddler is telling me that its a 500 error. What have I done wrong? I've placed a breakpoint on my controller however it doesnt get that far

2 Answers 2

5

Your URL should be:

'/Business/PreviewEmail'

instead of:

'/BusinessController/PreviewEmail'

However, the recommended practice for building URLs is to use your routes:

Url.Action("PreviewEmail", "Business")

BTW, you have another problem in your code. By setting "application/json" as your contentType, MVC will expect a JSON string. However, when you assign a JavaScript object to the data property of $.ajax(), jQuery will serialize the value to this:

email=1223

So you'll want to assign a string to the data property instead by doing this:

var p = '{ "email": "1223" }';

Sign up to request clarification or add additional context in comments.

Comments

0

@Url.Action doesn't work inside the JS file. What if my call to Controller/Action is inside JS file?

For now I'm, retrieving the location.href and then replacing the Action name. (This may not be a wise thing to do)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.