Unable to send array data using ajax with ASP.NET Core and Entity Framework Core - asp.net-mvc

I am trying to send array to the controller but it's blank in the controller parameter.
Ajax function is:
$('#pending').click(function () {
SaveTestResult("/Reception/PatientTests/SavePendingTest");
});
function SaveTestResult(url) {
var pid = $('.patientId').attr('id');
var tid = "";
var tval = "";
var tpid = "";
var tests = [];
$("table > tbody > tr").each(function () {
testId = $(this).find('.tid').val();
if (typeof (testId) != "undefined") {
tid = testId;
}
var rowText = ""
$(this).find('td').each(function () {
tpid = $(this).find('.tpId').val();
tval = $(this).find('.result').val();
if (typeof (tpid) != "undefined") {
tests.push({ PatientId: pid, TestId: tid, TestParameterId: tpid, TestValue: tval });
}
});
});
// alert(JSON.stringify(tests));
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(tests),
contentType: "application/json",
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
success: function (data) {
alert(data);
},
error: function (e) {
alert('Error' + JSON.stringify(e));
}
});
}
This is the controller method:
[HttpPost]
[Route("Reception/PatientTests/SavePendingTest")]
public async Task<IActionResult> SavePendingTest(List<PendingTestResult> pendingTestResult)
{
if (ModelState.IsValid)
{
foreach (PendingTestResult ptr in pendingTestResult)
{
_db.Add(ptr);
await _db.SaveChangesAsync();
}
// return new JsonResult("Index");
}
return new JsonResult(pendingTestResult); ;
}
But when run the code I see data array filled but inside of the SavePendingTest action, pendingTestResult is empty and not filled! I also tried the [FromBody] tag inside action params, but it does not work either!
Help me resolve this

you are sending a string with no names so the controller can not get the values.
change you code to
$.ajax({
type:"POST",
url:url,
data:test
...
});
the test should be an object not a string.

You can pass the list of objects by :
$.ajax({
type: "POST",
url: "Reception/PatientTests/SavePendingTest",
data: { pendingTestResult: tests },
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
success: function (data) {
alert(data);
},
error: function (e) {
alert('Error' + JSON.stringify(e));
}
});
pendingTestResult in data:{ pendingTestResult: tests } matches the parameter name on action and remove the contentType setting .

Related

How can get image with Jquery Ajax

I can can get picture by Razor '#Action' but with Ajax Can't. I write
in controller:
public ActionResult getCommodityPic()
{
var f= File(Server.MapPath("~/App_Data/CommodityPics/eee/1") + ".jpg", "image/jpg");
return f;
}
and in java script :
$(document).ready(function () {
ShowCommodities();
getCommodityPic();
});
function getCommodityPic() {
$.ajax({
url: '#Url.action("getCommodityPic")',
type: 'Get',
dataType: 'image/jpg',
success: function (Data, Status, jqXHR) {
$('#img1').attr('src', Data);
}
});
$.ajax({
url: '#Url.Action("DownloadPic", "MyController")',
contentType: 'application/json; charset=utf-8',
datatype: 'json',
data: {
id: Id
},
type: "GET",
success: function (Data, Status, jqXHR) {
if (Data != "") {
alert("Empty");
return;
}
window.location ='#Url.Action("DonloadPic","Mycontroller")';
}
});
in Controller:
public ActionResult DownloadPic(int? id)
{
Lesson l = new Lesson();
l = db.Lesson.Single(p => p.id == id);
if (l.picture == null)
{
string targetFolder = System.Web.HttpContext.Current.Server.MapPath("~/Image/book-03.jpg");
byte[] img = System.IO.File.ReadAllBytes(targetFolder);
return File(img, "image/jpg");
}
return File(l.picture, "image/jpg");
}
If you want to display the image dynamically, then try this. You may not need an Ajax call for this.
$('#img1').html('<img src="getCommodityPic" />')
If you want to process the image (read its raw binary) then this answer should help - https://stackoverflow.com/a/20048852/6352160

Getting 500 error while return object to ajax call

I am getting error when I am trying to return result to my ajax call. Getting 500 error every time I try to return the data. Here is my ajax call:
I am getting error when I am trying to return result to my ajax call. Getting 500 error every time I try to return the data. Here is my ajax call:
$("#UserActivation").change(function () {
var userID = $("#UserActivation").val();
var searchPic;
var planID = $("#planid").val();
debugger;
$.ajax({
type: "GET",
url: "/Home/GetUserImage",
data: { userID: userID, type: 'Activation', planID: planID },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
debugger;
alert(response);
},
error: function (xhr, ajaxOptions, thrownError){
debugger;
alert(xhr.responseText);
},
complete: function (a) {
// Handle the complete event
debugger;
alert("ajax completed ");
}
});
return false;
});
And my Controller function is:
[HttpGet]
public JsonResult GetUserImage(string userID, String type, string planID)
{
if (userID != null && type != null && planID != null)
SaveUser(planID, userID, type);
DataSet ds = SQL_DB.ExecuteDataSet("SELECT * FROM [M_UserRegistration] where [ActiveFlag] = 1 and UserId='" + userID + "'");
UserData userData = new UserData();
if (ds.Tables[0].Rows.Count > 0)
{
userData.UserID = Convert.ToString(ds.Tables[0].Rows[0]["UserId"]);
userData.UserImage = "../../Images/Users/" + Convert.ToString(ds.Tables[0].Rows[0]["UserImage"]);
userData.UserName = Convert.ToString(ds.Tables[0].Rows[0]["UserFirstName"]) + " " + Convert.ToString(ds.Tables[0].Rows[0]["UserLastName"]);
}
return Json(userData);
}
Getting 500 error in the error of ajax.
You have to allow json data for request type GET like following. Hope this will solve your problem.
return Json(userData, JsonRequestBehavior.AllowGet);

observableArray sent as parameter to a contoller function is null

I want to pass the data in the FeatureList (observableArray) to the SaveMappings function in the TreeController. I have binded a button to the sendItems function. I put a breakpoint at the var data=p2fData line to see what I received. p2fData is null.
I changed the controller to public JsonResult SaveMappings(List p2fData). In this case p2f data shows that there is 1 element, but then its null too.
var Feature = function (featId) {
var self = this;
self.featId = featId;
self.parameters = ko.observableArray();
}
var ParameterToFeatureListViewModel = function () {
var self = this;
var newFeature = new Feature("Feature XYZ");
newFeature.parameters.push("1");
newFeature.parameters.push("2");
self.FeatureList = ko.observableArray([newFeature]);
self.sendItems = function() {
$.ajax({
type: "POST",
url: '/Tree/SaveMappings',
data: ko.toJSON(self.FeatureList),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
},
error: function (request, status, error) {
alert(request.statusText);
}
});
}
}
var vm = new ParameterToFeatureListViewModel()
ko.applyBindings(vm);
public class TreeController:Controller
{
public ActionResult Index(){...}
[HttpPost]
public JsonResult SaveMappings(string p2fData)
{
var data = p2fData;
return Json(data);
}
}
Please have a look # how to pass knockoutjs view model into a mvc controller
... May be it helps..

MVC: pass parameter to action using Jquery.ajax()

I'm pretty new to MVC. I need to make ajax call to an Action with parameters using html.Action(). I'm unable to pass this..
Hope it will be helpful for other MVC begineers as well..
HTML:
<%: Html.ActionLink("Add Race", "AddRace",
new {eventId = Model.EventId, fleetId=Model.SelectedFleet.ID},
new{#onclick=string.Format("return checkFleetAddedandScroing()")}) %>
Jquery:
function checkFleetAddedandScroing() {
debugger;
$.ajax({
type: "GET",
url: '<%=Url.Action("CheckFleetExists")%>',
dataType: "json",
cache: false,
success: function (data, textStatus) {
data = eval("(" + data + ")");
if (data == true) {
return true;
}
else {
alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
return false;
}
}, //success
error: function (req) {
}
});
}
Action:
public JsonResult CheckFleetExists(Guid fleetId )
{
bool exists = false;
try
{
exists = !db.Races.Any(r => r.FleetID == fleetId);
}
catch
{
}
return Json(exists, JsonRequestBehavior.AllowGet);
}
I need to pass fleetid to action which is in Model.SelectedFleet.ID. Its being used somewhere on pages. But i'm unable to use that somehow..
please suggest where i'm doing wrong...
It looks like you are trying to invoke a controller action using AJAX when the link is clicked and depending on the result of this call either allow the user to be redirected to the actual AddRace action or be prompted with an error message.
The problem with your code is that you are attempting to return true/false from within the success AJAX callback which doesn't make any sense. You need to always return false from the click callback and inside the success callback, depending on the returned value from the server, redirect manually using the window.location.href function.
HTML:
<%: Html.ActionLink(
"Add Race",
"AddRace",
new {
eventId = Model.EventId,
fleetId = Model.SelectedFleet.ID
},
new {
data_fleetid = Model.SelectedFleet.ID,
#class = "addRace"
}
) %>
Jquery:
<script type="text/javascript">
$(function () {
$('.addRace').click(function (evt) {
$.ajax({
type: 'GET',
url: '<%= Url.Action("CheckFleetExists") %>',
cache: false,
data: { fleetId: $(this).data('fleetid') },
success: function (data) {
if (data.exists) {
// the controller action returned true => we can redirect
// to the original url:
window.location.href = url;
}
else {
alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
}
},
error: function (req) {
}
});
// we make sure to cancel the default action of the link
// because we will be sending an AJAX call
return false;
});
});
</script>
Action:
public ActionResult CheckFleetExists(Guid fleetId)
{
bool exists = false;
try
{
exists = !db.Races.Any(r => r.FleetID == fleetId);
}
catch
{
}
return Json(new { exists = exists }, JsonRequestBehavior.AllowGet);
}
Remark: inside your AddRace controller action don't forget to perform the same verification as you are doing inside your CheckFleetExists. The user could simply disable javascript and the AJAX call will never be done.
change your action like this :
public JsonResult CheckFleetExists(string fleetId)
{
var fleetGuid = Guid.Parse(fleetId);
bool exists = false;
try
{
exists = !db.Races.Any(r => r.FleetID == fleetGuid );
}
catch
{
}
return new JsonResult{ Data = exists};
}
and change you ActionLink so :
<%: Html.ActionLink("Add Race", "AddRace",
new {eventId = Model.EventId, fleetId=Model.SelectedFleet.ID},
new{onclick=string.Format("return checkFleetAddedandScroing({0})",Model.SelectedFleet.ID)}) %>
and your script block may look something like this :
function checkFleetAddedandScroing($fleetId) {
$.ajax({
type: "POST",
url: '<%=Url.Action("CheckFleetExists")%>',
dataType: "json",
data : { "fleetId" : $fleetId },
cache: false,
success: function (data, textStatus) {
data = eval("(" + data + ")");
if (data == true) {
return true;
}
else {
alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
return false;
}
}, //success
error: function (req) {
}
});
}
Problem was in answers that url to action was not complete..i did it using this way
function checkFleetAddedandScroing() {
// debugger;
$.ajax({
type: "POST",
url: '<%=Url.Action("CheckFleetExists", new {eventId=Model.EventId})%>',
dataType: "json",
cache: false,
success: function (data, textStatus) {
data = eval("(" + data + ")");
if (data == true) {
return true;
}
else {
alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
return false;
}
}, //success
error: function (req) {
}
});
}

MVC serialize object, list of objects, collections in Json

Parsing json returned from the controller. For some reason when returning a dictionary I need to do "ToString()" on the key element, otherwise I get an error. Why?. Are the samples below the correct way/best way to serialize json? thanks
Controller:
// JSON
public ActionResult GizmosJsonObject()
{
var gizmo = new Gizmo
{
Id = 2343,
Name = "Some awesome name",
Quantity = 32,
IntroducedDate = DateTime.Now
};
return this.Json(gizmo);
}
public ActionResult GizmosJsonObjectCollection()
{
var gizmos = new List<Gizmo>();
gizmos.Add(new Gizmo
{
Id = 102,
Name = "some name1",
Quantity = 535,
IntroducedDate = DateTime.Now
});
gizmos.Add(new Gizmo
{
Id = 122,
Name = "some name1",
Quantity = 135,
IntroducedDate = DateTime.Now
});
gizmos.Add(new Gizmo
{
Id = 562,
Name = "some name1",
Quantity = 2,
IntroducedDate = DateTime.Now
});
return this.Json(gizmos);
}
public ActionResult GizmosJsonListInts()
{
var gizmos = new List<int>();
gizmos.Add(2);
gizmos.Add(56);
gizmos.Add(32);
return this.Json(gizmos);
}
public ActionResult GizmosJsonDictionaryInts()
{
var gizmos = new Dictionary<int, int>();
gizmos.Add(23, 123);
gizmos.Add(26, 227);
gizmos.Add(54, 94323);
return this.Json(gizmos.ToDictionary(x => x.Key.ToString(), y => y.Value));
}
public ActionResult GizmosJsonDictionaryStrings()
{
var gizmos = new Dictionary<string, string>();
gizmos.Add("key1", "value1");
gizmos.Add("Key2", "value2");
gizmos.Add("key3", "value3");
return this.Json(gizmos);
}
View:
<script type="text/javascript">
/*<![CDATA[*/
$(function () {
// json object
$("a.Object").click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("GizmosJsonObject", "Home")',
contentType: 'application/json',
type: 'POST',
success: function (json) {
console.log(json.Id);
console.log(json.Name);
console.log(json.IntroducedDate);
// format date
var date = new Date(parseInt(json.IntroducedDate.substr(6)));
console.log(date);
}
});
});
// json object collection
$("a.ObjectCollection").click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("GizmosJsonObjectCollection", "Home")',
contentType: 'application/json',
type: 'POST',
success: function (json) {
$(json).each(function () {
console.log(this.Id);
console.log(this.Name);
console.log(this.IntroducedDate);
// format date
var date = new Date(parseInt(this.IntroducedDate.substr(6)));
console.log(date);
});
}
});
});
// json list of ints
$("a.ListInts").click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("GizmosJsonListInts", "Home")',
contentType: 'application/json',
type: 'POST',
success: function (json) {
$(json).each(function (i, e) {
console.log(json[i]);
});
}
});
});
// json dictionary of ints
$("a.DictionaryInts").click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("GizmosJsonDictionaryInts", "Home")',
contentType: 'application/json',
type: 'POST',
success: function (json) {
for (var key in json) {
if (json.hasOwnProperty(key)) {
var value = json[key];
console.log(key);
console.log(value);
}
}
}
});
});
// json dictionary of strings
$("a.DictionaryStrings").click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("GizmosJsonDictionaryStrings", "Home")',
contentType: 'application/json',
type: 'POST',
success: function (json) {
for (var key in json) {
if (json.hasOwnProperty(key)) {
var value = json[key];
console.log(key);
console.log(value);
}
}
}
});
});
});
/*]]>*/
</script>
A JSON key must be of the type string. See the right sidebar here http://www.json.org/ where it states that a pair must take the form of string: value.
Just for corroboration, this document here http://www.ietf.org/rfc/rfc4627.txt states the following:
2.2. Objects
An object structure is represented as a pair of curly brackets
surrounding zero or more name/value pairs (or members). A name is a
string. A single colon comes after each name, separating the name
from the value. A single comma separates a value from a following
name. The names within an object SHOULD be unique.

Resources