Reputation: 327
I'm working in ASP MVC & C#, and what i'm trying to do is something similar to the following.
public JsonResult SendMessage(SMSTestViewModel model)
{
if (//logic here)
{
string phonenumber = model.phone.ToString();
string derp = string.Empty;
//SMS.SendSMS(phonenumber, "testing heheheheh", derp);
var result = new { Success = "True", Message = "Good Job" };
return Json(result, JsonRequestBehavior.AllowGet);
}
var result = new { Success = "False", Message = "Didn't work" };
return Json(result, JsonRequestBehavior.AllowGet);
}
That's the code block in my controller, and now I'm trying to reference this in my View with the following
<p>Please enter your phone number</p>
<table>
<tr>
<td>Phone Number</td>
<td> <input id = "phone" type ="text" name= "phone" /></td>
</tr>
</table>
<input type="button" value="Submit" id="sendMSG">
<script>
$('sendMSG').click(function(){
$.getJSON('SMSTestController/SendMessage', function (data) {
alert(data.Success);
alert(data.Message);
});
});
</script>
For some reason the alerts wont show up. And It's quite confusing to me. I'm really new to JSON, JQuery and Javascript so any help or recommendations would be greatly appreciated.
Thanks
EDIT:
Changed the html code block to the following:
<input type="button" value="Submit" id="sendMSG">
<script>
$('#sendMSG').click(function () {
$.getJSON('@Url.Action("SendMessage","SMSTestController")', function (data) {
alert(data.Success);
alert("test");
alert(data.Message);
});
});
</script>
Upvotes: 0
Views: 1240
Reputation: 8276
Changing the url to the following should make it work
'/SMSTestController/SendMessage'
However, the better solution is as Matt had mentioned
'@Url.Action("SendMessage", "SMSTestController")'
Also, Have a look at this Fiddle http://jsfiddle.net/Ukuyc/
Upvotes: 1
Reputation: 36103
Most likely, the URL in your $.getJSON
call is incorrect. You have it relative to whatever URL you're currently looking at.
Try changing that line to be:
$.getJSON('@Url.Action("SendMessage", "SMSTestController")', function (data) {
This way, MVC generates an absolute URL to your action.
Edit:
Your jQuery selector of your button is wrong.
$('sendMSG')
Since you're searching for it by id, use:
$('#sendMSG')
Upvotes: 2