JsonResult has no name, how do I access the values - asp.net

I have a linq query in my controller that returns values from the database in JSON format. However The JSON object has no name so I tried a couple things but everything returns undefined.
My JSON object looks like:
Object {UserId: 4, UserName: "John", UserPassword: "Password"}
Controller
[HttpPost]
public JsonResult Index(string searchString, string searchPassword)
{
var user = (from u in db.Users where u.UserName.Equals(searchString) && u.UserPassword.Equals(searchPassword) select u).FirstOrDefault();
return Json(user);
}
Ajax
$('#test2').click(function(e) {
e.preventDefault();
var user = "John";
var userpass = "Password";
$.ajax({
url: "#Url.Action("Index", "Users")",
data: { "searchString": user, "searchPassword": userpass },
type: "post",
success: function (data) {
var results = [];
for (var i = 0; i < data.length; i++) {
results[data[i]["Key"]] = data[i]["Value"];
}
alert((result.UserName));
alert((result.UserPassword));
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr, ajaxOptions, thrownError);
}
})
})
The alerts come up with just undefined

You should be able to access the object by just using the properties from your C# object. So in your ajax success function, just use data.UserId or data.UserName

Do this in your ajax success
success: function (data) {
var results = [];
for (var i = 0; i < data.length; i++) {
result.push(data[i].UserId +" "+ data[i].UserName);
}
alert(result);
}

Related

Uncaught ReferenceError: data is not defined // can't get the date in ajax

Can't load my data, i guess something is wrong with getting the date. Here's my ajax:
function refreshdata(page) {
dates = '{ "date": "2017-05-12T09:14:15Z" }';
if (page == 1) {
$.ajax({
url: semRoute,
type: 'GET',
success: function (result) {
var data = JSON.parse(result);
showData(data);
}
});
}
console.log(page);
}
AjaxController:
public string Get(string date)
{
var obj = new DepDate(date);
return Model.balance.GetDataJSON(obj);
}

data table (View) not refreshing after jQuery Ajax call in mvc

I'm facing below issue while refreshing data that has been POSTed using Ajax in MVC. The POST is successfully being executed, but the data on the VIEW does not get refreshed with the new data. When I debug, the values from the Ajax POST are successfully being passed to my controller. When the controller returns the view model return View(objLMT);, my VIEW is not refreshing the new data. How do I get the new data to show in my VIEW?
AJAX
function getAllUserRoleCompany() {
debugger
var url = '#Url.Action("GetAllUserRoleCompany", "UserRoleCompany")';
var Organisation = $("#Organisation").val();
if (Organisation == "All") {
Organisation = "";
}
else {
Organisation = Organisation;
}
var RoleName = $("#RoleName").val();
if (RoleName == "All") {
RoleName = "";
}
else {
RoleName = RoleName;
}
var i = 0;
if ($("#UserName").find("option:selected").length >= 0) {
var len = $("#UserName").find("option:selected").length;
}
else {
len = 0;
}
var UserName = "";
for (; i < len; i++) {
if ($("#UserName").find("option:selected")[i].text != "All") {
if (i == 0) {
UserName = "',";
}
if (i < len - 1) {
UserName += $("#UserName").find("option:selected")[i].text + ",";
UserName = UserName.substring(0, UserName.indexOf("-")) + ",";
}
else {
UserName += $("#UserName").find("option:selected")[i].text + ",'";
UserName = UserName.substring(0, UserName.indexOf("-")) + ",'";
}
}
}
if (UserName == "All") {
UserName = ""
}
else {
UserName = UserName;
}
var UserStatus = $("#UserStatus").val();
if (UserStatus == "All") {
UserStatus = "";
}
else {
UserStatus = UserStatus;
}
$.ajax({
url: url,
data: { Organisation: Organisation, RoleName: RoleName, UserName: UserName, UserStatus: UserStatus },
cache: false,
type: "POST",
success: function (data) {
//$("#dataTables-example").bind("");
//$("#dataTables-example").bind();
//location.reload(true);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
Below is the view code on the same page
<div class="row">
#Html.Partial("pv_UserRoleCompany", Model)
Controller
public ActionResult GetAllUserRoleCompany(String Organisation, String RoleName, String UserName, int UserStatus)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
string usrNameWithDomain = System.Web.HttpContext.Current.User.Identity.Name;
//string userID = "261213"; // Environment.UserName;
string userID = "100728";
ViewBag.UserRoleId = objLMTDAL.GetRoleID(userID);
objLMT.TypeList = objLMTDAL.UserRoleCompany_GetAll(Organisation, RoleName, userID, ViewBag.UserRoleId, UserName, UserStatus);
// return Json(objLMT, JsonRequestBehavior.AllowGet);
return PartialView("pv_UserRoleCompany", objLMT);
}
With above code My while SEARCHING or UPDATING view my table/Grid is not refreshing.
Kindly help.
If you are returning a partial view from an AJAX call you have to use jQuery to "refresh" the data.
In your js code you can do this:
$.ajax({
url: url,
data: { Organisation: Organisation, RoleName: RoleName, UserName: UserName,
UserStatus: UserStatus },
cache: false,
type: "POST",
success: function (data) {
//$("#dataTables-example").bind("");
//$("#dataTables-example").bind();
//location.reload(true);
$("#dataTables-example").html(data);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
This will replace the existing HTML with the one from the partial view result in your controller.
#Mihail I have tried using the above solution. It Works I mean it refreshes my view but It's not loading my view perfectly as expected.
View Before (Expected)
View After using $("#dataTables-example").html(data);
Try if this works for you
Call this function as per your call:
function getAllUserRoleCompany(parameters) {
var token = $('[name=__RequestVerificationToken]').val();
$.ajax({
type: "POST",
url: '/UserRoleCompany/GetAllUserRoleCompany',
data: { Organisation: Organisation, RoleName: RoleName, UserName: UserName, UserStatus: UserStatus },
dataType: 'html',
success: function (data) {
$("#").empty().html(data);
}
});
}

Ajax call not passing arrays to controller action

I am passing an array variable to the controller.
Array from ajax call contains data but after calling the controller it shows count=0.
var url = '#Url.Action("UserRoleCompany_AddUserAccess", "UserRoleCompany")';
$.ajax({
url: url,
data: { userIDs: userIDs, Organisation: Organisation, RoleName: RoleName, userIDsLength: userIDsLength, UserStatus: UserStatus },
cache: false,
type: "POST",
success: function (data) {
location.reload(true);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
Controller code below,
public ActionResult UserRoleCompany_AddUserAccess(List<int> userIDs, string Organisation, string RoleName, int userIDsLength,int UserStatus)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
objLMTDAL.UserRoleCompany_AddUserAccess(Organisation, RoleName, userIDsLength, UserStatus);
return RedirectToAction("Index");
}
And below are a screenshot for reference,
You can not pass an array as a parameter in ajax,you can either convert userIDs to a json string or combine them as a string,then pass to the controller side.
More details information can be found at Why the array will not send through the ajax call?
#lucumt
I have tried the same thing with table - selecting the multiple rows from the table and send it to the controller and it is working fine.
Please check below and let me know.
var url = '#Url.Action("UserRoleCompany_UpdateUserAccess", "UserRoleCompany")';
$.ajax({
url: url,
data: { Ids: checkedIds, newUserStatus: UserStatus },
cache: false,
type: "POST",
success: function (data) {
location.reload(true);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
Controller
public ActionResult UserRoleCompany_UpdateUserAccess(List<int> Ids, int newUserStatus)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
string userRoleIds = String.Join(",", Ids);
objLMTDAL.UserRoleCompany_UpdateUserAccess(userRoleIds, newUserStatus);
return RedirectToAction("Index");
//return RedirectToAction("Index", "UserRoleCompany");
}
You can check the live scenario below in screenshots,

IFormFile is always empty in Asp.Net Core WebAPI

I have a problem here when I am trying to push data with angularjs controller. But what ever I do (IFormFile file) is always empty. There are only some examples with razor syntax but no examples how to do it with angular or jquery.
HTML:
<form class="form-body" enctype="multipart/form-data" name="newFileForm" ng-submit="vm.addFile()"><input type="file" id="file1" name="file" multiple ng-files="getTheFiles($files)"/></form>
Directive:
(function() {
'use strict';
angular
.module('app')
.directive('ngFiles', ['$parse', function ($parse) {
function fn_link(scope, element, attrs) {
var onChange = $parse(attrs.ngFiles);
element.on('change', function (event) {
onChange(scope, { $files: event.target.files });
});
};
return {
link: fn_link
};
}]);
})();
Controller
var formdata = new FormData();
$scope.getTheFiles = function ($files) {
angular.forEach($files, function (key, value) {
formdata.append(key, value);
});
};
vm.addFile = function () {
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-Type", "undefined");
xhr.send(formdata);
}
Asp.net core webapi:
[HttpPost]
public async Task<IActionResult> PostProductProjectFile(IFormFile file)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
....
return ...;
}
I have also tried to do it with formdata, as it is constructed when you post it with razor syntax. Something like this:
dataService.addFile(formdata, {
contentDisposition: "form-data; name=\"files\"; filename=\"C:\\Users\\UserName\\Desktop\\snip_20160420091420.png\"",
contentType: "multipart/form-data",
headers: {
"Content-Disposition": "form-data; name=\"files\"; filename=\"C:\\Users\\UserName\\Desktop\\snip_20160420091420.png\"",
'Content-Type': "image/png"
},
fileName: "C:\\Users\\UserName\\Desktop\\snip_20160420091420.png",
name: "files",
length : 3563
}
Also instead of formData to provide raw file as I wrote in comment. But still nothing happens
IFormFile will only work if you input name is the same as your method parameter name. In your case the input name is 'files' and the method parameter name is 'file'. Make them the same and it should work.
This is how to do it with angularjs:
vm.addFile = function () {
var fileUpload = $("#file").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length ; i++) {
data.append(files[i].name, files[i]);
}
$http.post("/api/Files/", data, {
headers: { 'Content-Type': undefined },
transformRequest: angular.identity
}).success(function (data, status, headers, config) {
}).error(function (data, status, headers, config) {
});
}
And in web Api:
[HttpPost]
public async Task<IActionResult> PostFile()
{
//Read all files from angularjs FormData post request
var files = Request.Form.Files;
var strigValue = Request.Form.Keys;
.....
}
Or like this:
[HttpPost]
public async Task<IActionResult> PostFiles(IFormCollection collection)
{
var f = collection.Files;
foreach (var file in f)
{
//....
}
}
You can do it also with kendo upload much simpler:
$("#files").kendoUpload({
async: {
saveUrl: dataService.upload,
removeUrl: dataService.remove,
autoUpload: false
},
success: onSuccess,
files: files
});
From the answer of #Tony Steele.
Here is the code sample (Where to change/take care of)
.NET Core 3.1 LTS
[Route("UploadAttachment")]
[HttpPost]
public async Task<IActionResult> UploadAttachment(List<IFormFile> formFiles)
{
return Ok(await _services.UploadAttachment(formFiles));
}
AngularJS
var formFiles = new FormData();
if ($scope.files != undefined) {
for (var i = 0; i < $scope.files.length; i++) {
formFiles.append('formFiles', $scope.files[i]);
}
}

Trying to show a value and description in Jquery UI Autocomplete, not showing data, what am I doing wrong?

I have been all over looking to try and solve my issue. I am thinking it may be on my back end but not sure. I am trying to use autocomplete to fill in a textbox but show in the drop down a description with the value.
My Method for grabbing the Data:
[WebMethod]
public static ArrayList GetQueries(string id)
{
queries q;
var cs = Global.CS;
var con = new SqlConnection(cs);
var da = new SqlDataAdapter(querystring, con);
var dt = new DataTable();
da.Fill(dt);
ArrayList rows = new ArrayList(dt.Rows.Count);
for (int i = 0; i < dt.Rows.Count; i++)
{
var val = dt.Rows[i]["Query_ID"];
var des = dt.Rows[i]["Description"];
q = new queries();
q.label = val.ToString();
q.value = val.ToString() + " -- " + des.ToString();
var json = new JavaScriptSerializer().Serialize(q);
rows.Add(json);
}
return rows;
}
public class queries
{
public string label { get; set; }
public string value { get; set; }
}
It is returning an arraylist.
My JQuery Method to get data and autocomplete.
$("[id$=QueryManager]").change(function () {
var id = $("[id$=QueryManager] :selected").val();
$.ajax({
type: 'POST',
url: 'Upload.aspx/GetQueries',
data: JSON.stringify({ id: id }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
fillit(data);
},
error: function (ex) {
alert('Request Status: ' + ex.status + '\n\nStatus Text: ' + ex.statusText + '\n\n' + ex.responseText);
}
});
});
function fillit(data) {
$("#QueryTxt").autocomplete({
delay: 0,
minLength: 0,
source: function (data, response) {
response($.map(data, function (item) {
return {
label: item.label,
value: item.value
}
}));
}
});
};
I have tried it with both the serialize and without to no results. When this code runs it shows that autocomplete is working (via the box showing up below) but there is no data in it.
I am not sure what I am doing wrong, any help is appreciated.
What I'm doing below is that on the "Select" event I take the values returned from the query and set the text of the drop down to the description and Id value from the data brought back. Then I set a dummy textbox's value as the description. "colDescName" is just a variable I was using as my textbox id.
$("#" +colDescName).autocomplete({
minLength: 2,
select: function( event, ui )
{
var rowElement=event.target.id;//Drop down Id
setTimeout(function()
{
$("#"+rowElement).val(ui.item.value+':'+ui.item.id)
},100);//need a slight delay here to set the value
$("#TextBoxId").val(ui.item.value);
//ui.item.value is the description in the drop down.
//ui.item.id is the Id value from the drop down
},
source: function (request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
lastXhr = $.getJSON("Upload.aspx/GetQueries", request, function (data, status, xhr) {
cache[term] = data;
if (xhr === lastXhr) {
response(data);
}
}).error(function () {
console.log("error");
});
}
});
What object is "$("[id$=QueryManager]")" that you have the change method on? Would you need the change event if you can use the above code?
EDIT
OK an easier way is set your textbox "$("#QueryTxt")" to an autocomplete box before executing any change events on your "QueryManager" manager dropdown. Then when a change event does occur in your "QueryManager" , call:
$(this).autocomplete('search', 'your data here');
That will then execute the search function and call the autocomplete's url with your required data

Resources