Reputation: 942
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.
Upvotes: 1
Views: 71
Reputation: 3122
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.
Upvotes: 0
Reputation: 24957
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.
Upvotes: 1
Reputation: 1089
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);
}
}
});
Upvotes: 1
Reputation: 204
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 );
}
});
Upvotes: 0