how can i pass an array in window.location without ajax call - javascript

I want to send list array in ExportTo Method, but in ExportTo method student parameter get null value. If I use ajax it will work fine. But have to use window.locatoin for pass list array.
View
$(document).ready(function () {
$("#SaveBtn").click(function () {
var student = {
Name: "Tanzid",
Department: "CSE"
};
var student1 = {
Name: "Yasir",
Department: "BBA"
};
var list = [];
list.push(student);
list.push(student1);
var url = '#Url.Action("ExportTo", "Students")';
var a = JSON.stringify(list);
window.location = url + '?' + a;
});
})
.
Controller
Public void ExportTo(List<Student> student)
{
}

Iv'e tested some scenario of your problem and its work without using ajax:
Commented first your code coz i don't have it.
From Index View:
#{
ViewBag.Title = "Index";
}
<script src="~/scripts/jquery-1.10.2.js"></script>
<h2>Index</h2>
<script>
$(document).ready(function () {
var person = [];
person.push("Reign");//change like $("#idname").val();
person.push("John");
var listOfObjects = [];
person.forEach(function (names) {
var singleObj = {}
singleObj['name'] = names;
singleObj['dept'] = 'IT Dept.';
listOfObjects.push(singleObj);
});
var url = '#Url.Action("Sample", "Home")';
window.location = url + '?id=' + JSON.stringify(listOfObjects);
})
HomeController:
public ActionResult Sample()
{
string getval = Request.QueryString["id"];
string concat = #"{""data"":" + getval + "}";
ValList vl = new JavaScriptSerializer().Deserialize<ValList>(concat);
foreach (var item in vl.data)
{
Console.WriteLine("dept: {0}, name: {1}", item.dept, item.name);
}
return View();
}
public class ValList
{
public List<Values> data { get; set; }
}
public class Values
{
public string name { get; set; }
public string dept { get; set; }
}
It's all working its just depend on your project code with this:
//var List = [];
//var a = {
// Name: $("#").val(),
// Dept: $("#").val()
//};
//List.Push(a);
This is all i got..
It's Tested according to your needs.. Good Luck

Related

.net Core Using razor function in Javascript

Hi i got to use c# code in js. My js and .cshtml page are separeted . I wrote a function in .cshtml page and gotta call it in .js file.
In Js file
DataList.forEach(function (item) {
...
var users = GetUsers(item.AssignedUsers);
It goes here
Index.cshtml
<script>
function GetUsers(userIdList) {
//it logs it, i can get theese values from here
console.log("userIdList");
console.log(userIdList);
#{ // but in here it says userIdList does not exist in current content
//also tryed this.userIdList
var users = userIdList.Split(",");
foreach (var item in users)
{
var user = _Manager.FindByIdAsync(item.UserId).Result;
}
}
}
</script>
You can pass list from ajax to controller action,and action return a list you want.
Here is a demo:
<button onclick="sendData()">
send
</button>
<script>
function sendData() {
//here is a sample list
var list = [];
var user1 = {};
user1.Id = 1;
user1.Name = "u1";
list.push(user1);
var user2 = {};
user2.Id = 2;
user2.Name = "u2";
list.push(user2);
$.ajax({
type: "POST",
url: '#Url.Action("SendData", "Test")',
contentType: "application/json",
data: JSON.stringify(list),
}).done(function (data) {
console.log(data);
//the data is you want
});
}
</script>
action:
public List<User> SendData([FromBody]List<User> list) {
//you can do something and return a list you want here
return list;
}
User:
public class User {
public int Id { get; set; }
public string Name { get; set; }
}
result:

ASP.Net MVC: How could i pass js array to mvc action by #Url.Action()

We know that we can pass js variable value to mvc action but how could i pass js array to mvc action ?
So my question is how could i pass js array to mvc action by #Url.Action() ?
please see my sample code
[HttpPost]
public ActionResult DoSomething(string id, string deptno, list<PdfInputs> PdfInputs)
{
// Some magic code here...
}
var id = "10";
var deptno = "C001";
var PdfInputs = [];
for(inti=0;i<=totalbol-1;i++)
{
var PdfInput = {
firstName: "John",
lastName: "Doe",
age: 46
};
}
PdfInputs.push(BOLPdfInput);
location.href = '#Url.Action("DoSomething", "Customer")?id=' + id + '&deptno=' + deptno;
my mvc action will download pdf at client and that is why i use
location.href = '#Url.Action("DoSomething", "Customer")?id=' + id + '&deptno=' + deptno;
please guide me.
Actually you can pass JSON string from array with #Url.Action() helper using query string parameter like this:
<script>
$(function() {
var id = "10";
var deptno = "C001";
var PdfInputs = [];
for (var i = 0; i < totalbol; i++)
{
PdfInputs.push({
firstName: "John",
lastName: "Doe",
age: 46
});
}
location.href = '#Url.Action("DoSomething", "Customer")?id=' + id + '&deptno=' + deptno + '&PdfInputs=' + JSON.stringify(PdfInputs);
})
</script>
However I strongly discourage this practice because passed JSON string may exceeds query string limit if the array has large amount of data. Additionally, you cannot use #Url.Action() helper for action method marked with [HttpPost] attribute (it only works for GET method), hence I recommend to use jQuery.ajax() to pass PdfInputs array as List<PdfInputs> & TempData/Session state variable to store file contents, then download PDF file using HttpGet controller action as provided below:
jQuery
<script>
$(function() {
var id = "10";
var deptno = "C001";
var PdfInputs = [];
for (var i = 0; i < totalbol; i++)
{
PdfInputs.push({
firstName: "John",
lastName: "Doe",
age: 46
});
}
$('#buttonid').click(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("DoSomething", "Customer")',
// traditional: true,
data: $.param({ id: id, deptno: deptno, pdfInputs: PdfInputs }, true),
success: function (result) {
location.href = '#Url.Action("Download", "ControllerName")?id=' + id;
},
error: function (err) {
// error handling
}
});
});
})
</script>
Controller (DoSomething Action)
[HttpPost]
public ActionResult DoSomething(string id, string deptno, List<PdfInputs> pdfInputs)
{
// Some magic code here...
// Save file to TempData or Session state
byte[] fileContent = fileStreamInstance.ToArray();
TempData["FileToDownload"] = fileContent;
return Json("Success");
}
Controller (Download Action)
[HttpGet]
public ActionResult Download(string id)
{
string fileName = "yourfilename.pdf";
// other code here
if (TempData["FileToDownload"] != null)
{
byte[] content = TempData["FileToDownload"] as byte[];
return File(content, "application/pdf", fileName);
}
else
{
return new EmptyResult();
}
}
Click on this fiddle https://dotnetfiddle.net/RRwK1K
View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut123</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
$("#theButton").click(function () {
var id = "10";
var deptno = "C001";
var PdfInputs = [];
var i;
for (i = 0; i <= 3; i++) {
PdfInputs.push({
firstName: "John",
lastName: "Doe",
age: 46
});
}
var json = JSON.stringify(PdfInputs);
location.href = '#Url.Action("theActionPassArray", "Home")?json=' + json;
})
})
</script>
</head>
<body>
<input type="button" id="theButton" value="Go" />
#*credit to https://stackoverflow.com/questions/15112055/passing-dynamic-javascript-values-using-url-action*#
#if (ViewBag.Data != null)
{
<span>The data sent to the server was:</span>#ViewBag.Data
}
</body>
</html>
Controller
public class PassArray
{
public string firstName { get; set; }
public string lasttName { get; set; }
public string age { get; set; }
}
public class HomeController : Controller
{
public ActionResult theActionPassArray(string json)
{
/turn json passed value into array
//You need to get NewtonSoft.JSON
PassArray[] arr = JsonConvert.DeserializeObject<PassArray[]>(json);
//put breakpoint here
ViewBag.Data = json;
return View("Tut123"); }
public ActionResult Tut123()
{
return View();
}

.net core Razor pages with JQuery AJAX

I am trying to call a Razor Page Handler using JQuery AJAX. Here is the sample code.
<script type="text/javascript">
$(document).ready(function () {
$("#SectionId").change(function () {
var options = {};
options.url = $(location).attr('href') + "/?SectionId=" + $("#SectionId").val() + "?handler=SelectByID";
options.type = "GET";
options.dataType = "json";
options.success = function (data) {
};
options.error = function () {
$("#msg").html("Error while making Ajax call!" + options.error.val);
};
$.ajax(options);
});
});
</script>
Razor Page cs code:
public class CreateModel : PageModel
{
private readonly ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);
[BindProperty]
public FileRecord FileRecord { get; set; }
public List<SelectListItem> UserList { get; set; }
public string SelectedSectionId { get; set; }
public CreateModel(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
{
_context = context;
_userManager = userManager;
}
public IActionResult OnGetSelectByID(string SectionId)
{
return null;
}
public async Task<IActionResult> OnGetAsync()
{
//Prepare UserList
UserList = new List<SelectListItem>();
List<ApplicationUser> Users = await _context.Users.ToListAsync();
foreach (var item in Users)
{
string role = Enum.GetName(typeof(EmRoles), EmRoles.NormalUser);
if (await _userManager.IsInRoleAsync(item, role) && item.IsEnabled)
{
UserList.Add(new SelectListItem()
{
Text = item.FullName,
Value = item.Id
});
}
}
//Sections
ViewData["Sections"] = new SelectList(_context.Sections, "Id", "Name");
//FileNOs
ViewData["Files"] = new SelectList(_context.FileRegisters, "Id", "FileNo");
//ViewData["ReceiverUserId"] = new SelectList(_context.Users, "Id", "Id");
//ViewData["SenderUserId"] = new SelectList(_context.Users, "Id", "Id");
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
//Two File Records have to be created. One For Sender & One for receiver.
FileRecord SenderRecord = new FileRecord
{
//create unique file id
//FileId = Guid.NewGuid().ToString(),
OutDate = DateTime.Now,
};
FileRecord ReceiverRecord = new FileRecord
{
//create unique file id
//FileId = SenderRecord.FileId,
InDate = SenderRecord.OutDate,
};
//Current logged-in user
var user = await GetCurrentUserAsync();
SenderRecord.OwnerUserId = user.Id;
//Receiver
ReceiverRecord.OwnerUserId = FileRecord.ReceiverUserId;
ReceiverRecord.SenderUserId = SenderRecord.OwnerUserId;
//Sender Record
if (await TryUpdateModelAsync<FileRecord>(SenderRecord, "FileRecord", f => f.FileId, f => f.Remarks, f => f.Gist, f => f.ReceiverUserId))
{
//Receiver Record
if (await TryUpdateModelAsync<FileRecord>(ReceiverRecord, "FileRecord", f => f.FileId, f => f.Gist))
{
_context.FileRecords.Add(SenderRecord);
_context.FileRecords.Add(ReceiverRecord);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
//If it reaches here. that means some error occurred.
return null;
}
}
The Issue is am not getting a call to Razor Page Handler defined above. If i skip the SectionId parameter passed-in & call only the handler. it is working fine. but it is not working when parameter is sent to the handler, default OnGet() is being called.
Help plz.
You don't need to append your handler parameter
options.url = $(location).attr('href') + "/?SectionId=" + $("#SectionId").val();
You also need to decorate the method with the HttpGet attribute
[HttpGet("GetSelectByID")]
public IActionResult OnGetSelectByID(string SectionId)
{
return null;
}
Then your URL to call this method needs to be
http://localhost:xxxx/FileMovement/Create/GetSelectByID?SectionId=yyy
When you have more than one GET defined on a controller you must tag the additional GET methods with the HttpGet attribute and add a string to define the name of that method.
Finally i was able to solve the issue.
<script type="text/javascript">
$(document).ready(function () {
$("#SectionId").change(function () {
var options = {};
options.url = $(location).attr('href') + "?handler=SelectByID" + "&SectionId=" + $("#SectionId").val();;
options.type = "GET";
options.dataType = "json";
options.success = function (data) {
};
options.error = function (data) {
$("#msg").html("Error while making Ajax call!" + data.error.val);
};
$.ajax(options);
});
});
Everything was right except i have to use "&" in "&SectionId="

Object array in FormData passing 0 objects to controller

I'm making an ajax call to the controller passing the FormData(), which has an array of objects along with few other properties. In my controller, the list array which I'm passing seems to have 0 elements. Please help!
Script in cshtml view -
var _getFormDataToJson = function () {
var applyDetail = [];
$(_tb).find('tbody tr').each(function (i, v) {
var trans = {
effectiveDate: $(this).find('.effectiveDate').val(),
amount: $(this).find('.amount').val(),
empLeaveHdID: $('#tx-leaveHdID').val(),
//attachmentUrl: $(this).find('.leaveAttachment')[0].files[0]
}
applyDetail.push(trans);
});
var formObj = new FormData();
formObj.append('remark', $('#tx-remark').val());
formObj.append('leaveAppType', $('#hdnLeaveAppType').val());
formObj.append('applyDetail', applyDetail); //this collection has 0 items in controller
return formObj;
}
var _sumbitForm = function () {
var formData2 = _getFormDataToJson();
$.ajax({
url: '#Url.Action("ApplyLeave", "Leave")',
type: 'POST',
processData: false,
contentType: false,
data: formData2,
//data: { data: formData2 },
success: function (data) {
if (data.success) {
_myToastr.success(data.msg[0], true, function () {
location.reload();
});
$(_modal).modal('close');
}
else {
_myToastr.error(data.msg[0]);
}
},
complete: function () {
}
});
}
Controller -
[HttpPost]
public JsonResult ApplyLeave(Hr_LeaveApplyHd data)
{
foreach (var detail in data.applyDetail) //applyDetail count is 0 here
{
//to DO:
}
return new JsonResult();
}
EDIT:
Hr_LeaveApplyHd model -
public class Hr_LeaveApplyHd
{
public Hr_LeaveApplyHd()
{
applyDetail = new List<ApplyDetail>();
}
[Key]
public int applyID { get; set; }
public string remark { get; set; }
public virtual List<ApplyDetail> applyDetail { get; set; }
public LeaveAppType leaveAppType { get; set; }
}
applyDetail model -
public class ApplyDetail
{
[Key]
public int applyDetialID { get; set; }
public DateTime effectiveDate { get; set; }
public decimal amount { get; set; }
public int empLeaveHdID { get; set; }
}
You cannot append arrays and/or complex objects to FormData. You need to append name/value pairs for each property of ApplyDetail and for each item in the collection, and with indexers, for example
formObj .append('applyDetail[0].effectiveDate', '09/19/2017');
which you could do in your $.each loop, for example
var formObj = new FormData();
formObj.append('remark', $('#tx-remark').val());
formObj.append('leaveAppType', $('#hdnLeaveAppType').val());
$(_tb).find('tbody tr').each(function (i, v) {
var name = 'applyDetail[' + i + '].effectiveDate';
var value = $(this).find('.effectiveDate').val();
formObj.append(name, value);
... // ditto for other properties
});
However, if you have generated your form correctly using the strongly typed HtmlHelper methods, including generating the controls for the collection property using a for loop of EditorTemplate for typeof ApplyDetail so they have the correct name attributes to match your model, then all you need is
var formObj = new FormData($('form').get(0));
which will correctly serialize all the form controls

JSON.parse for array of object

Server returns the array of object in JSON. It looks so:
{"d":"[
{\"Id\":1,\"IsGood\":true,\"name1\":\"name1dsres\",\"Name2\":\"name2fdsfd\",\"name3\": \"name3fdsgfd\",\"wasBorn\":\"\\/Date(284011000000)\\/\"},
{\"Id\":2,\"IsGood\":false,\"name1\":\"fdsfds\",\"name2\":\"gfd3im543\",\"name3\":\"3543gfdgfd\",\"WasBorned\":\"\\/Date(281486800000)\\/\"}
]"}
I need to parse using JSON.parse function. I'm doing this this way:
function myFunction(dataFromServer){
var parsedJSON = JSON.parse(dataFromServer.d);
for (var item in parsedJSON.d) {
// how do I get the fields of current item?
}
This code is not working, it returns undefined
for (var item in parsedJSON) {
alert(item.Id);
}
This works perfectly
function myFunction(dataFromServer){
var parsedJSON = JSON.parse(dataFromServer.d);
for (var i=0;i<parsedJSON.length;i++) {
alert(parsedJSON[i].Id);
}
}
But this doens't
function myFunction(dataFromServer){
var parsedJSON = JSON.parse(dataFromServer.d);
for (var item in parsedJSON) {
alert(item.Id);
}
}
You can just access them as you would any object:
var id = item.Id;
if (item.IsGood) { ... }
If you wish to enumerate them to use somehow, have a look at this SO question.
You can access them as you do oridinary javascript objects,
that is either as item.id or item['id']
class Program
{
static void Main(string[] args)
{
var jsonString = #"{
""data"": [
{
""uid"": ""100001648098091"",
""first_name"": ""Payal"",
""last_name"": ""Sinha"",
""sex"": ""female"",
""pic_big_with_logo"": ""https://m.ak.fbcdn.net/external.ak/safe_image.php?d=AQAi8VLrTMB-UUEs&bust=1&url=https%3A%2F%2Fscontent-a.xx.fbcdn.net%2Fhprofile-ash2%2Fv%2Ft1.0-1%2Fs200x200%2F10018_433988026666130_85247169_n.jpg%3Foh%3Dc2774db94dff4dc9f393070c9715ef65%26oe%3D552CF366&logo&v=5&w=200&h=150"",
""username"": ""payal.sinha.505"",
},
]
}";
dynamic userinfo = JValue.Parse(jsonString);
IList<FacebookUserDetail> userDeatils = new List<FacebookUserDetail>();
// 1st method
foreach (dynamic userinfoItr in userinfo.data)
{
FacebookUserDetail userdetail= userinfoItr.ToObject<FacebookUserDetail>();
userDeatils.Add(userdetail);
}
// 2nd Method
var userDeatils1 = JsonConvert.DeserializeObject<FacebookUserDetails>(jsonString);
}
}
public class FacebookUserDetail
{
public string username { get; set; }
//Password = EncryptionClass.Md5Hash(Guid.NewGuid().ToString()),
public string first_name { get; set; }
public string last_name { get; set; }
public string sex { get; set; }
public string pic_big_with_log { get; set; }
}
enter code here
public class FacebookUserDetails
{
public IList<FacebookUserDetail> data { get; set; }
}
}

Categories

Resources