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.
-
Do you know about Ajax ? BTW, no point in returning Redirect response from action method when called via Ajax.Shyju– Shyju2018年10月27日 05:57:40 +00:00Commented 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.Syntax Rommel– Syntax Rommel2018年10月27日 05:59:32 +00:00Commented Oct 27, 2018 at 5:59
4 Answers 4
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);
}
}
});
-
There is no specific message about the error but for now I fall back to "error"Syntax Rommel– Syntax Rommel2018年10月27日 06:55:01 +00:00Commented Oct 27, 2018 at 6:55
-
use this to catch error: error: function(xhr, textStatus, error){ alert(xhr.statusText); alert(textStatus); alert(error); }Syed Md. Kamruzzaman– Syed Md. Kamruzzaman2018年10月27日 06:57:02 +00:00Commented Oct 27, 2018 at 6:57
-
use try{} catch(exception ex){throw ex;} in controller so u can get the exception.Syed Md. Kamruzzaman– Syed Md. Kamruzzaman2018年10月27日 07:00:17 +00:00Commented Oct 27, 2018 at 7:00
-
can't see any errors even I already put the try catch on my controller but the alert pops saying not foundSyntax Rommel– Syntax Rommel2018年10月27日 07:04:57 +00:00Commented Oct 27, 2018 at 7:04
-
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.pngSyed Md. Kamruzzaman– Syed Md. Kamruzzaman2018年10月27日 07:08:59 +00:00Commented Oct 27, 2018 at 7:08
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.