Sunday, February 27, 2011

Invoking an ASP.NET MVC function from jQuery

Given this:

<script type="text/javascript">
    function test() {
        $.ajax(
        {
            url: "/Music/Save/",
            type: 'POST',
            dataType: 'json',
            data:
            {
                Title: $("#Title").val(),
                Album: $("#Album").val(),
                YearReleased: $("#YearReleased").val()
            },
            success: function (result) {
                alert(result.Something);
            }
        });
    }
</script>


And this:

<input type="submit" value="Create" onclick="test(); return false;" />

And this model:
namespace SampleJquery.Models
{
    public class Song
    {
        public string Title { get; set; }
        public string Album { get; set; }        
        public int YearReleased { get; set; } 
    }
}

This is how your ControllerHere/MethodHere shall look like:

namespace SampleJquery.Controllers
{
    public class MusicController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Save(Song s)
        {
            return Json(new { Something = s.Title + " " + s.Album + " " + s.YearReleased.ToString() });
        }

    }
}


Notice that in jQuery's AJAX call, we don't invoke the full controller name, we just need to invoke the function using the controller's public url slash method:

url: "/Music/Save/",

No comments:

Post a Comment