简体   繁体   中英

ASP.NET MVC Controller Result return to view

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>

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')

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM