asp.net MVC call controller from javascript - 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.

Related

How can i fill a DropDown list using ajax and a c# method

Hi my c# method is this:
[WebMethod]
protected static void fillList(HiddenField hiddenControl, System.Web.UI.WebControls.DropDownList listinc)
{
int dato = 0;
string strSql;
dato = Convert.ToInt32(hiddenControl.Value);
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ToString());
conn.Open();
strSql = "SELECT DISTINCT incid FROM HisReportes WHERE peri = " + dato;
SqlCommand camAND = new SqlCommand(strSql, conn);
System.Data.DataTable tablainc = new System.Data.DataTable();
camAND.CommandTimeout = 36000;
tablainc.Load(camAND.ExecuteReader());
foreach (DataRow dtrw in tablainc.Rows)
{
listinc.Items.Add(dtrw[0].ToString());
}
}
i tested with a onlick function and it works but i need to call it from Ajax function:
$.ajax({
type: "POST",
url: "Incio.aspx/fillList",
data: '{hiddenControl , listinc, dtrw }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
$.each(data, function (){
$("listinc").append($("<option />").val(this.incidente).text(this.dtrw[0]));
});
},
failure: function () {
alert("Failed!");
}
});
that's my ajax function but it is not filling the dropdown list.
you need to return the list from your WebMethod, I recommended you to return a string array from the WebMethod.
[WebMethod]
public static string[] fillList()
{
your code here....
return listinc.ToArray();
}
So, into Ajax in the success function
$.ajax({
type: "POST",
url: "./Inicio.aspx/fillList",
...
success: function (data) {
let data = data["d"];
let dropdown = $("#listinc");
for (let i = 0; i < data.length; i++) {
// put here your data
dropdown.append(`<option>${ data[i] }</option>`);
}
}
});

'undefined' reported when bind gridview using AJAX in C#

I want to bind the gridview using AJAX. So, for that I done client side code using AJAX and server side code as a webmethod.
Everything is working fine even I alert the data in success method at that time also data is showing but in loop I really confused that it is showing undefined in alert. So for that's why grid is not binding.
Here is my code
$.ajax({
type: "POST",
url: "schoolregistration.aspx/GetGridData",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#grid_schooldata").append("<tr><td>" + data.d[i].schoolName);
}
},
failure: function () {
alert("error! try again...");
}
});
using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var cmd = new SqlCommand("select schoolname as [School Name] from tbl_schoolregistration", con))
{
con.Open();
object val = cmd.ExecuteScalar();
return val == DBNull.Value ? "" : (string)val;
}
First of all
ExecuteScalar Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
In this case you will have a single string.
Secondly beware of the name in your query leave it as schoolname not [School Name].
Then you have to Serialize into json and again parse into json in order to loop through objects.
Here is fully working code:
$.ajax({
type: "POST",
url: "schoolregistration.aspx/GetGridData",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
data = JSON.parse(data.d);
for (var i = 0; i < data.length; i++) {
$("#grid_schooldata").append("<tr><td>" + data[i].schoolname +"</td></tr>");
}
},
failure: function () {
alert("error! try again...");
}
});
[WebMethod]
public static string GetGridData()
{
using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var cmd = new SqlCommand("select schoolname from tbl_schoolregistration", con))
{
con.Open();
//object val = cmd.ExecuteScalar();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt); // fills data from select query
// return val == DBNull.Value ? "" : (string)val;
return JsonConvert.SerializeObject(dt);
}
}

Why occur Internal server error in my ajax query?

I want to pass some value to server and it has to return one string.
Jquery version
<script src="js/jquery-3.1.1.js"></script>
Here is my code:
$('#btnSaveFile').click(function () {
var fileName = $('#txtFileName').val();
alert(fileName);
$.ajax({
url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
method: 'GET', //method or type ?
contentType: 'application/json',
data: '{fileName:' + fileName +'}', //UPDATED Line
dataType: 'json',
success: function (data) {
alert('success');
alert(data.d.exist);
},
error: function (error) {
alert('fail');
alert(error);
}
});
});
Aspx code
[WebMethod]
public static string getFileExistOrNot(string fileName)
{
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select ReportData FROM [HQWebMatajer].[dbo].[ReportSave] where Userfilename=#UserFileName and ReportName=#ReportName";
cmd.Parameters.AddWithValue("#UserFileName", fileName);
cmd.Parameters.AddWithValue("#ReportName", "TotalSales");
con.Open();
var data = cmd.ExecuteScalar();
if (data != null)
{
string exist = "dataExist";
return exist;
}
else
{
string exist = "notExist";
return exist;
}
}
}
Error Msg
GET http://localhost:55047/ReportTotalSalesPivot.aspx/getFileExistOrNot?fileName:www} 500 (Internal Server Error)
ExceptionType:"System.InvalidOperationException"
Message:"An attempt was made to call the method 'getFileExistOrNot' using a GET request, which is not allowed."
StackTrace:" at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)
↵ at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)".
I think this error it occurs in server side. But I don't know what is that
Updated
Error Message:"Invalid web service call, missing value for parameter:'fileName'."
Send your data like below:
In object format
data: { fileName:fileName },
OR
As a String
data = "fileName="+filename;
After one day I found What was my mistake.
This is the answer
data:'{fileName:"'+fileName+'"}'

JavaScript - AJAX / 'Data' is empty / asp.net MVC

I found some similar questions but none of them resolve my problem.
The problem I have is that my data from my AJAX-call is empty but my controller return exactly I want him to return.
I tried to add a contentType, but neither contentType nor ContentType worked for me.
What am I doing wrong?
JavaScript:
function AddFunction() {
var ergebnis = "";
var zahl1 = $("#txt_1").val();
var zahl2 = $("#txt_2").val();
$.ajax({
async: false,
cache: false,
type: 'POST',
url: '/Calc/Add',
dataType: 'JSON',
data: {
'val_1': zahl1,
'val_2': zahl2
},
success: function (data) {
ergebnis = data.result;
alert(ergebnis);
},
error: function () {
alert("Fehler");
}
});
}
Controller:
public ActionResult Add(string val_1, string val_2)
{
string sUri = "http://192.168.111.173:35145/temppath/GVCalc/1.0/add";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(sUri);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"field_1\":\"" + val_1 + "\"," +
"\"field_2\":\"" + val_2 + "\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var result = DeserializeFromStream(httpResponse.GetResponseStream());
return Json(result);
}
Controller result:
{{
"result": 3
}}
Ajax data:
kinda empty / no result at all
Edit:
DeserializeFromStream Method:
public static object DeserializeFromStream(Stream stream)
{
var serializer = new JsonSerializer();
using (var sr = new StreamReader(stream))
using (var jsonTextReader = new JsonTextReader(sr))
{
return serializer.Deserialize(jsonTextReader);
}
}
I solved my problem by sending a string and parse it in JavaScript. This worked fine for me :)
C#:
return Json(result.ToString());
JavaScript:
var ergebnis_json = JSON.parse(data)
ergebnis = ergebnis_json.result;
$("#ergebnis").val(ergebnis);
Thanks everyone for their help :)

Return Array from Back End to Front End

[System.Web.Services.WebMethod]
public Array loaddata()
string sql = "SELECT Name,Time,Inuse FROM table4";
using (SqlConnection Connection = new SqlConnection((#"Data Source")))
{
using (SqlCommand myCommand = new SqlCommand(sql, Connection))
{
Connection.Open();
using (SqlDataReader myReader = myCommand.ExecuteReader())
{
DataTable dt = new DataTable();
dt.Load(myReader);
Connection.Close();
DataView dv = new DataView(dt);
dv.RowFilter = (("Name='ACVX'"));
var tableEnumerable = dv.ToTable().AsEnumerable();
var tableArray = tableEnumerable.ToArray();
return tableArray ;
}
}
}
//Front End
<html>
<head/>
<script>
PageMethods.loaddata(LoadSucc, LoadFail);
function LoadSucc(obj) //obj is array returned from back end{obj-tablearray]
{
var goog = [];
goog = Object.values(obj);
//I want load the obj into my array goog.
}
function LoadFail() {
alert("Data missing");
}
script>
<body/>
<html>
I want to Load my data table content to array and return array to front end using page methods.I tried somethingbut it won't working.What's wrong with My Code?
Suggest me some Ideas
Hi Try to call your webmethod with Jquery ajax funtion like this:
<html>
<head/>
<script>
$.ajax({
type: "POST",
url: "/yourpagename.aspx/loaddata",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var dataArray = $.map(data, function (item) {
return item;
});
alert(dataArray);
console.log(dataArray);
},
error: function (data) {
alert("ajax error " + data);
}
});
script>
<body/>
<html>

Categories