MVC calling controller from javascript - javascript

I've got an MVC view that is successfully calling a controller. In the controller, I call a stored procedure (using entity framework) and get some results. That part of it all works fine. But, I'm unable to get my results back from my javascript. When I have it as an ActionResult, all is fine, I just can't seem to get to the result. When I try to change it to a JsonResult, I keep getting an "Internal Server" error, so I'm not sure which way to go. Any pointers would help (I'm not a great javascript/jquery developer).
My javascript:
var jqXHR = $.ajax({
method: 'POST',
url: varurl,
data: { text: tempField, letterId: "2" },
cache: false,
success: function (results) { alert(results) }
})
.done(function (result) {
$('#content').empty();
$('#content').html(result);
$('#content').html(result);
})
.error(function (xhr, status, error) {
alert(error);
});
//letterArea.value = letterArea.value + title[0] + "\r\n" + "\r\n" + title[1] + "\r\n" + "\r\n";
letterArea.value = "Hello";
}
My Controller:
public ActionResult ResolveText(string text, string letterId)
{
using (LMNEntities db = new LMNEntities())
{
var results = db.ResolveFieldsForLetter(Convert.ToInt32(letterId),text);
return View(results);
}
}

Related

How to use KnockoutJS to save data into SQL database?

Good day everybody. I have a question about how to use the right way to save data into SQL database through KnockoutJs. The record are display well in the table. It should be able to save the data via this pop-up Modal. But after I click the Create button in that modal, it only pop-up a failed Message. Can anybody please help me to solve this problem? Thank you very much.
Below is extract from main js file about Save function
var data = ko.toJSON(self.Profiles());
$.ajax({
type: 'POST',
url: '/ajaxCall/insertProAjax',
data: "{ Customer:" + ko.utils.stringifyJson(self.Name) + ",customerRemove:" + ko.utils.stringifyJson(self.CustomerRemove) + "}",
contentType: "application/json",
success: function (data) {
alert("Record has been saved Successfully");
MarkCustomerAsSaved();
$('#AddNewModel').modal('hide');
},
error: function () {
alert("Failed");
}
}).fail(function (xhr, textStatus, err) { alert(err); });
Below is extract from the ViewModel about save function
var Customer = {};
Customer.Id = c.Id;
Customer.Name = c.Name;
Customer.Age = c.Age;
Customer.Address = c.Address;
if (isNewRecord === false) {
$.ajax({
type: "PUT",
url: "/api/CustomerAPI/" + c.Id,
data: Customer
})
.done(function (resp) {
self.Message("Record Updated Successfully ");
self.reset();
})
.fail(function (err) {
self.Message("Error Occures, Please Reload the Page and Try Again " + err.status);
self.reset();
});
}
if (isNewRecord === true) {
isNewRecord = false;
$.ajax({
type: "POST",
url: "/api/CustomerAPI",
data: Customer
})
.done(function (resp) {
self.Message("Record Added Successfully ");
self.reset();
loadData();
}).fail(function (err) {
self.Message("Error Occures, Please Reload the Page and Try Again " + err.status);
self.reset();
});
}
Knockout and Javascript (in this manner) are being processed client side. You will need to create something on the back end to accept your data payload and save it to the database. If you want to stay in the JavaScript family, I would recommend
node.js. Alternatively this is where php, or C# would come into play.

Passing an array Of Objects Into An MVC .net core Controller Method Using jQuery Ajax

am using .netcore 1.1 , Visual studio 2017 , Jquery version = "3.2.1"
,am trying to make the MVC controller to get data from my page ,
i have 2 arrays in java , one is an array of Object (model view) and one is an array of strings
objects array always return error 400 (bad request)
2- string array ,always send null to the controller
i followed the below answers with no success
https://stackoverflow.com/a/13255459/6741585
and
https://stackoverflow.com/a/18808033/6741585
below is my chtml page
//#region send data back t oserver
$('#Savebtn').click(function () {
console.log(editedRows);
var UpdatedRows = JSON.stringify({ 'acActivityed': editedRows });
console.log(UpdatedRows);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/acActivity/Edit",
//traditional: true,
data: UpdatedRows ,
dataType: "json",
success: function (data) {
// here comes your response after calling the server
alert('Suceeded');
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error : " + jqXHR.responseText);
}
});
});
//#endregion
//#region deleted all selected
$('#DeleteSelectedbtn').on('click', function () {
if (confirm("Are you sure to delete All Selected ?????")) {
var selectedData = [];
var selectedIndexes;
selectedIndexes = grid.getSelectedRows();
jQuery.each(selectedIndexes, function (index, value) {
selectedData.push(grid.getDataItem(value).id);
});
console.log(selectedData);
var SelectedIds = selectedData.join(',') ;
console.log(SelectedIds);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/acActivity/DeleteSelected",
data: JSON.stringify({ "ids": SelectedIds }),
dataType: "json",
success: function (data) {
grid.render();
},
error: function (err) {
alert("error : " + err);
}
});
}
});
//#endregion
and both do have data as below console shots
the selected ID's one
my Controller
this one should expect the list of object and always return bad request ,
[HttpPost]
[ValidateAntiForgeryToken]
//public jsonResult Edit( List<acActivitytbl> acActivityed)
public ActionResult Edit( List<acActivitytbl> acActivityed)
{
foreach (acActivitytbl it in acActivityed)
{
logger.Log(LogLevel.Info, it.ID);
logger.Log(LogLevel.Info, it.Name);
logger.Log(LogLevel.Info, it.IsActive);
}
//return View(acActivityed);
return Json(new { success = true, responseText = "end of Page" });
}
that one should expect the delimited string ,but always receive null
public ActionResult DeleteSelected(string ids)
{
try
{
char[] delimiterChars = { ' ', ',', '.', ':', ' ' };
string[] words = ids.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
if (words != null && words.Length > 0)
{
foreach (var id in words)
{
bool done = true; //new acActivitiesVM().Delete(Convert.ToInt32(id));
logger.Log(LogLevel.Info, " acActivities ID {0} is Deleted Scussefully ", id);
}
return Json(new { success = true, responseText = "Deleted Scussefully" });
}
return Json(new { success = false, responseText = "Nothing Selected" });
}
catch (Exception dex)
{
..... removed to save space
});
}
}
i know there is something missing here ,but i cannot find it ,any help in that ??

ajax request not sending any data ASP.NET MVC project with jQuery

I'm fairly new to asp.net MVC but am baffled as to why my request isn't working.
I'm trying to send an ajax request with jquery as per:
jQuery(function ($) {
var total = 0,
share = $('div.share'),
googlePlusUrl = "https://plusone.google.com/_/+1/fastbutton?url=http://bookboon.com" + $(location).attr('pathname');
setTimeout(function() {
$.ajax({
type: 'GET',
data: "smelly",
traditional: true,
url: share.data('proxy'),
success: function(junk) {
//var $junk = junk.match(regex);
console.log(junk);
},
error: function (xhr, errorText) {
console.log('Error ' + xhr.responseType);
},
});
}, 4000);
And set a line in my RouteConfig as:
routes.MapRoute(null, "services/{site}/proxy", new { controller = "Recommendations", action = "Proxy" });
The markup has a data-attribute value as:
<div class="share" data-proxy="#Url.Action("Proxy", "Recommendations")">
And my Proxy action method starts with:
public ActionResult Proxy(string junk)
The problem is that the junk parameter is always null. I can see in the debug output that the route seems to correctly redirect to this method when the page loads (as per jQuery's document ready function), but I cannot seem to send any data.
I tried sending simple data ("smelly") but I don't receive that neither.
Any suggestions appreciated!
The model binder will be looking for a parameter in the request called junk, however you're sending only a plain string. Try this:
$.ajax({
type: 'GET',
data: { junk: "smelly" }, // <- note the object here
traditional: true,
url: share.data('proxy'),
success: function(junk) {
//var $junk = junk.match(regex);
console.log(junk);
},
error: function (xhr, errorText) {
console.log('Error ' + xhr.responseType);
},
});

Ajax Post always returns an error

Hi i am trying to call a C# method to return a json but keep getting errors.
$.ajax({
type: 'POST',
url: 'ReportList.aspx/GetReports',
dataType: 'json',
success: function (response) {
dataset = response.d;
},
error: function (response, success, error) {
alert("Error: " + error);
}
});
The error i am getting reads as:
Unexpected token <
Previously i had contentType: 'application/json; charset=utf-8', added but that returned a internal server error.
I would like to call json so that i may populate a javascript.datatable.
C# Function:
public string GetReports()
{
System.Data.DataSet d;
d = (System.Data.DataSet)Session["dsHistory"];
System.Data.DataSet DsNew = new System.Data.DataSet("cdreports");
System.Data.DataTable table1 = new System.Data.DataTable("reports");
table1.Columns.Add("id");
table1.Columns.Add("name");
table1.Columns.Add("regAndId");
table1.Columns.Add("type");
table1.Columns.Add("timeStamp");
foreach (System.Data.DataRow row in d.Tables["company"].Rows)
{
table1.Rows.Add(row["rc_id"], row["companyname"], row["companyregnumber"], "Company", row["rc_timestamp"]);
}
foreach (System.Data.DataRow row in d.Tables["director"].Rows)
{
table1.Rows.Add(row["rd_id"], row["firstname"] + " " + row["surname"], row["idnumber"], "Director", row["rd_timestamp"]);
}
DsNew.Tables.Add(table1);
string json = JsonConvert.SerializeObject(DsNew, new DataSetConverter());
return json;
}
Make sure trace is disabled on the page. Sometimes ajax calls don't work if page tracing is enabled.

Posting JSON string to ASP.NET MVC 3 action results in null parameter

I am posting a JSON string to asp.net MVC as follows.
AJAX call
$.ajax({
type: "POST",
url: "#(storeLocation)IDR/OpcInsertCustomerProfile/",
data: JSON.stringify(currSelection),
contentType: "application/json",
success: function(data) {
alert('success : ' + JSON.stringify(data));
},
error: function(data) {
alert('Error : ' + JSON.stringify(data));
}
}
);
In the controller:
[HttpPost]
[ActionName("OpcInsertCustomerProfile")]
public JsonResult OpcInsertCustomerProfile(string currSelectionData)
{
try
{
JavaScriptSerializer ser = new JavaScriptSerializer();
var res = ser.Serialize(currSelectionData);
return Json(currSelectionData, JsonRequestBehavior.AllowGet);
}
catch (Exception exc)
{
return Json(new { error = 1, message = exc.Message });
}
}
Debugger indicates the action gets called successfully, however the incoming string parameter being received is always null. Firebug 'post' shows outgoing parameter is proper json object. I am expecting to see the JSON string as incoming parameter. Please note that I don't want to de-serialise it into proper object. All I want to do is store the string in JSON format 'as-it-is' in a database. Later on it needs be retrieved ans passed to Javascript as it is.
Try this :
$.ajax({
type: "POST",
url: "#(storeLocation)IDR/OpcInsertCustomerProfile/",
data: { "currSelectionData" : "'" + JSON.stringify(currSelection) + "'" },
contentType: "application/json",
success: function(data) {
alert('success : ' + JSON.stringify(data));
},
error: function(data) {
alert('Error : ' + JSON.stringify(data));
}
}
);
One way is to allow the action to receive the parameter as POST data instead of JSON "Stringified" data. To do that, post the data without JSON.Stringify. Hopefully this is what you need.
If not you might want to try creating an object just to receive this simple data.
Look at your action method: is it correct that method accepts string with serialized JSON, than serialized that string as JSON again and then dismiss the result and serializes and returns the same string again?
If you send request with application/json type ASP.NET MVC tries to deserialize received string and bind it to action parameters: in your case it tries to find property currSelectionData inside your JSON object. Is that property exists? Maybe you expect whole string is received as currSelectionData parameter? Then you need to use FormCollection or Request.Form instead because default model binder does not support this.
Actually i fill my state dropdown in selection of country with json i do like this
in my controller i have action it's return my data in json format like this it's below
public JsonResult State(int countryId)
{
var stateList = CityRepository.GetList(countryId);
return Json(stateList, JsonRequestBehavior.AllowGet);
}
in my view
<script type="text/javascript">
function cascadingdropdown() {
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
var countryID = $('#countryID').val();
$.ajax({
url: "/City/State",
dataType: 'json',
data: { countryId: countryID },
success: function (data) {
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
$.each(data, function (index, optiondata) {
alert(optiondata.StateName);
$("#stateID").append("<option value='" + optiondata.ID + "'>" + optiondata.StateName + "</option>");
});
},
error: function () {
alert('Faild To Retrieve states.');
}
});
}
</script>
i think this will help you...
When sending json through Ajax, I think this is the right approach for the data property in Ajax:
data: "{'parameterNameInAction':'" + JSON.stringify(jsonData) + "'}"

Categories

Resources