1

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.

2
  • Do you know about Ajax ? BTW, no point in returning Redirect response from action method when called via Ajax. Commented Oct 27, 2018 at 5:57
  • just a little, I saw some online reference that they are using it but I am struggling how can I convert my current logic to that. Commented Oct 27, 2018 at 5:59

4 Answers 4

1

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);
  }
      }
    });
Sign up to request clarification or add additional context in comments.

6 Comments

There is no specific message about the error but for now I fall back to "error"
use this to catch error: error: function(xhr, textStatus, error){ alert(xhr.statusText); alert(textStatus); alert(error); }
use try{} catch(exception ex){throw ex;} in controller so u can get the exception.
can't see any errors even I already put the try catch on my controller but the alert pops saying not found
u need to change table name like use tilt before and after table name MyTable. my sql treat in this way. try this i.sstatic.net/aWYml.png
|
1

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.

Comments

0

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 );
  }
});

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.