Search code examples
jqueryajaxasp.net-mvcbackbone.js

How to perform Ajax Call using backbone js in MVC


I have the following JavaScript code:

App.Views.AddPerson = Backbone.View.extend({
        el: '#addPerson',

        events: {
            'submit': 'submit',
        },

        submit: function (e) {
            e.preventDefault();
            var newPersonName = $(e.currentTarget).find('input[type=text]').val();
            var person = new App.Models.Person({ name: newPersonName, age: newAge, occupation: newOccupation });
            this.collection.add(person);
            this.$('#todo-title').val('');

            $.ajax({
              type: 'POST',
              url: '@Url.Action("InsertRecord", "Home")',
              data: newPersonName ,
              success: function(data) {
                alert(data);
              },
              error: function(){
                alert("error");
              }
            });
        }
    });

In the controller I have following method:

[HttpPost]
    public ActionResult InsertRecord(string str)
    {

        return View();
    }

But it is not perform the ajax call and raise the error.


Solution

  • Try this:

     submit: function (e) {
            e.preventDefault();
            var newPersonName = $(e.currentTarget).find('input[type=text]').val();
            var person = new App.Models.Person({ name: newPersonName, age: newAge, occupation: newOccupation });
            this.collection.add(person);
            this.$('#todo-title').val('');
    
           $.ajax({
            type: 'POST',
            url: window.location + "Home/InsertRecord",
            data: {ID : newPersonName},
            success: function(data) {
            // Code after success },
              error: function(){
              alert("error");
              }
           });