简体   繁体   中英

asp.net MVC call controller from javascript

Is there a way that I can call my insert function from controller using my javascript from the view

Here is my controller:

       public ActionResult Update(int a, string b)
        {
            string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
            using (MySqlConnection con = new MySqlConnection(constr))
            {
                MySqlCommand cmd = new MySqlCommand("UPDATE MyTable SET a = @a WHERE b = @b ", con);
                //cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@a", a);
                cmd.Parameters.AddWithValue("@b", b);                
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
            return RedirectToAction("Index");
        }

And here is my javascript that holds values from HTML

     function SaveChanges() {
        var a = document.getElementById("a").value
        var b = document.getElementById("b").value

        //TODO: pass the variables to the controller to perform insert query
    }

Any suggestions or comments. TIA.

Please try this:

 function submit(){
    var a = document.getElementById("a").value;
    var b = document.getElementById("b").value;
    $.ajax({
      url: '/ControllerName/Update(ActionResult)/' 
      type: 'post',
      contentType: 'application/json',
      data: {
        'a':a,
        'b':b
      },
      success: function(data){
        alert('success');
      }, 
      error: function(xhr, textStatus, error){
      alert(xhr.statusText);
      alert(textStatus);
      alert(error);
  }
      }
    });

What you want is using AJAX callback to call the controller action from client-side, which should be set up like example below:

JS function

function SaveChanges() {
    // input values
    // the variable names intentionally changed to avoid confusion
    var aval = $('#a').val();
    var bval = $('#b').val();

    var param = { a: aval, b: bval };

    $.ajax({
        type: 'POST',
        url: '@Url.Action("Update", "ControllerName")',
        data: param,
        // other AJAX settings
        success: function (result) {
            alert("Successfully saved");
            location.href = result; // redirect to index page
        }
        error: function (xhr, status, err) {
            // error handling
        }
    });
}

Then add [HttpPost] attribute to the controller action and return JSON data which contains URL to redirect, because RedirectToAction() does not work properly with AJAX callback:

Controller action

[HttpPost]
public ActionResult Update(int a, string b)
{
    string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    using (MySqlConnection con = new MySqlConnection(constr))
    {
        MySqlCommand cmd = new MySqlCommand("UPDATE MyTable SET a = @a WHERE b = @b ", con);
        cmd.Parameters.AddWithValue("@a", a);
        cmd.Parameters.AddWithValue("@b", b);                
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }

    // create URL and return to view
    string redirectUrl = Url.Action("Index", "ControllerName");

    return Json(redirectUrl);
}

Note that this is just a simple example, you can improve with try...catch exception handling and other things not mentioned here.

you should use jquery Ajax POST method for that . such as this structure...

function submit(){
var a = document.getElementById("a").value
var b = document.getElementById("b").value
$.ajax({
  url: '/ControllerName/Update/' 
  dataType: 'text',
  type: 'post',
  contentType: 'application/json',
  data: {
    'a':a,
    'b':b
  },
  success: function( data, textStatus, jQxhr ){
    alert('success')
    console.log(data)
  }, 
  error: function( jqXhr, textStatus, errorThrown ){
    console.log( errorThrown );
  }
});

Controller Code

public ActionResult Update(int a, string b)
{
    string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    using (MySqlConnection con = new MySqlConnection(constr))
    {
        MySqlCommand cmd = new MySqlCommand("UPDATE MyTable SET a = @a WHERE b = @b ", con);
        //cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@a", a);
        cmd.Parameters.AddWithValue("@b", b);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
    return RedirectToAction("Index");
}

.cshtml Code

function SaveChanges() {
  var a = document.getElementById("a").value;
  var b = document.getElementById("b").value;

  $.ajax({
    type: 'GET',
    url: '@Url.Action("Update")',
    data: {
      'a': a,
      'b': b
    },
    success: function(result) {
      alert("Successfully saved");
    },
    error: function(xhr, status, err) {
      // error handling code
    }
  });
}

You need to call the SaveChanges() function on the submit button click event. Based on your reference code I have to make the method as GET , in case your method on controller side is POST , then in AJAX method you need to change method type GET to POST .

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