Pass javascript array to C# code Razor pages - javascript

I have the following JavaScript code in Index.cshtml
function getActivity()
{
var collection = document.getElementsByClassName("skill-icon-selected");
const splitCollection = new Array;
for (var i = 0; i < collection.length; i++)
{
var split = collection[i].id.split("-");
splitCollection.push(split[0]);
}
console.log(splitCollection);
}
I want to pass the array splitCollection to Index.cshtml.cs to use
public List<Activity> allActivities = new List<Activity>();
public void OnGet()
{
allActivities = _context.Activities.ToList();
foreach (var activity in allActivities)
{
if (splitCollection.contains(activity.Skill))
{
//Do stuff
}
}
How would I access splitCollection in my cshtml.cs or the data in splitCollection to be usesd in c#

Since you want to pass an array to cshtml.cs in razor page,you need to use Post method.So you can pass data to OnPost handler,here is a demo:
cshtml:
#Html.AntiForgeryToken()
#section Scripts{
<script>
function getActivity() {
var collection = document.getElementsByClassName("skill-icon-selected");
const splitCollection = new Array;
for (var i = 0; i < collection.length; i++)
{
var split = collection[i].id.split("-");
splitCollection.push(split[0]);
}
console.log(splitCollection);
$.ajax({
type: "POST",
url: "",
data: JSON.stringify(splitCollection),
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
contentType: "application/json",
success: function (data) {
}
});
console.log(splitCollection);
}
</script>
}
cshtml.cs:
public void OnPost([FromBody] List<Activity> myAllActivities)
{
...
}

Related

How to POST Data from HTML Page via WebApi in MVC Controller

Function which is use to take input data from HTML
function saveclickdata()
{
var allData = {
InvNo:document.getElementById('TbInvNo').value,
GrossSale:document.getElementById('TbOrderTotal').value,
discount:document.getElementById('TbDiscount').value,
CusCash:document.getElementById('TbCash').value,
CusBal:document.getElementById('TbBalance').value,
};
$.ajax({
url: "\Controllers\POSController.cs\SaveData",
type: 'POST',
data: allData,
success: function (res) {
alert("success");
},
error: function (err) {
alet("Error");
}
});
Api which is in controller used to post data
[HttpPost]
JsonResult SaveData(POSMater collection)
{
if (collection.InvNo.ToString() == null)
{
var LocalInvNo = (from b in db.TblPOSMasters select b).FirstOrDefault();
int MaxInvNo = Convert.ToInt32(LocalInvNo) + 1;
collection.InvNo = MaxInvNo;
TblPOSMaster master = new TblPOSMaster();
master.InvNo = collection.InvNo;
master.AddBy = 1;
master.AddDate = DateTime.Now;
master.CashStatus = "A";
master.CompId = 1;
//master.CreditAmt = collection.CreditAmt;
//master.CrCardNo = collection.CrCardNo;
master.CusCash = collection.CusCash;
master.CusId = 1;
master.GrossSale = collection.GrossSale;
db.TblPOSMasters.Add(master);
db.SaveChanges();
}
else
{
return Json(collection);
}
return Json(collection);
}
What should i do? My html button working properly but still not able to call api
I think you ought to use forward slashes (/) in your URL

Api from Asp core controller not receive all the value that FormData.append(key,value) appended

I want to upload files(image, setup file) and some other text string together.
This is my ajax code:
function uploadFiles(inputId) {
var input = document.getElementById(inputId);
var files = input.files;
formData = new FormData();
for (var i = 0; i !== files.length; i++) {
var temp1 = files[i];
}
formData.append('temp', 1);
formData.append('temp', "ksjhdfksdjf");
$.ajax({
type: "POST",
url: "/Admin/FileUploadView/SaveEntity",
data: formData,
contentType: false,
processData: false,
beforeSend: function () {
tedu.startLoading();
},
success: function () {
},
error: function () {
}
});
}
This is my controller:
When I log all the files that formData object contain, everything is ok:
But I only receive 2 image's objects in the controller:
Now I want that I can receive all the files that I appended. Do you have any ideas, please help me.
You do not receive your temp in your controller.
js:
function uploadFiles(inputId) {
var input = document.getElementById(inputId);
var files = input.files;
var formData = new FormData();
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]);
}
formData.append('temp', 1);
formData.append('temp', "ksjhdfksdjf");
//ajax
controller:
[HttpPost]
public async Task<IActionResult> SaveEntity(IList<IFormFile> files,List<string> temp)

DropDownList with java script

I hope developers can support me, I have minimal experience in the use of java script.
After investigating and several attempts, I was able to load a dropdownlist with data from a LINQ query and pass as a parameter the value of a textbox.
What I could not do is from the query Linq get two fields (Id and value) send them to the dropdownlist and show the value but after being able to use the Id of that field to be able to use it in a create, currently I can only show the value but I need the Id too.
View
#Html.TextBox("CP", "", new { #id = "txtCP", #onchange = "FillOption();", #placeholder = "Codigo Postal" })
#Html.DropDownList("Asentamientos", ViewBag.Drop as List<SelectListItem>)
Script
<script>
function FillOption() {
var CP = $('#txtCP').val();
$.ajax({
type: "Post",
url: "/Home/GetAsentamiento",
data: { CP: CP },
dataType: 'json',
success: function (data) {
$("#Asentamientos").empty();
for (var i = 0; i < data.length; i++) {
$('#Asentamientos').append('<option value=' + data[i].Value + '>' + data[i].Text + '</option > ');
}
}
});
}
</script>
Controllers
public ActionResult Index()
{
List<SelectListItem> drop = new List<SelectListItem>
{
};
ViewBag.Drop = drop;
return View();
}
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select p.Asentamiento).ToList();
SelectList lista = new SelectList(drop2);
ViewBag.lista = lista;
return Json(ViewBag.lista);
}
I think of something like
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { p.IdCodigoPostal,p.Asentamiento}).ToList();
SelectList lista = new SelectList(drop2);
ViewBag.lista = lista;
return Json(ViewBag.lista);
}
but I do not know how the id and the value would be handled
Thanks
If I understand your question correctly, I think you need to name the fields of the object you are creating with the Linq expression, so that it would look something like this:
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { id = p.IdCodigoPostal, value = p.Asentamiento}).ToList();
SelectList lista = new SelectList(drop2);
ViewBag.lista = lista;
return Json(ViewBag.lista);
}
Here are a few examples: https://code.msdn.microsoft.com/LINQ-to-DataSets-09787825#SelectAnonymousTypes1
Then you could access those fields from you javascript with data[i].id and data[i].value.
I hope this helps.
I suspect your issue is around pulling the data from the API result. You're setting the a new property in the ViewBag, then returning the ViewBag property. This really shouldn't be required, and you should instead just return your list, list so (Note: and SelectItemList has a property called "Items" which contains all items you've added):
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { p.IdCodigoPostal,p.Asentamiento}).ToList();
SelectList lista = new SelectList(drop2);
return Json(lista.Items);
}
This should return just a nice list of ListItems. You could also just change your jQuery to loop through the items property, like so:
<script>
function FillOption() {
var CP = $('#txtCP').val();
$.ajax({
type: "Post",
url: "/Home/GetAsentamiento",
data: { CP: CP },
dataType: 'json',
success: function (data) {
$("#Asentamientos").empty();
for (var i = 0; i < data.Items.length; i++) {
$('#Asentamientos').append('<option value=' + data.Items[i].Value + '>' + data.Items[i].Text + '</option > ');
}
}
});
}
</script>
Thanks to all, the code works as follows
Controller
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { Value = p.IdCodigoPostal, Text= p.Asentamiento }).ToList();
SelectList lista = new SelectList(drop2);
return Json(lista.Items);
}
Script
<script>
function FillOption() {
var CP = $('#txtCP').val();
$.ajax({
type: "Post",
url: "/Home/GetAsentamiento",
data: { CP: CP },
dataType: 'json',
success: function (data) {
$("#Asentamientos").empty();
for (var i = 0; i < data.length; i++) {
$('#Asentamientos').append('<option value=' + data[i].Value + '>' + data[i].Text + '</option > ');
}
}
});
}

Refresh model after post-request in ASP.MVC

I'm developping a webApp with MVC.
I have a view with cirkles displaying a value and a slider,
when you slide the cirkles need to display the new value.
I send the new value with a POST from my AJAX call to the controller,
which does a minor calculation with the value and give it back to the view
so the cirkles can display the updated value.
However my view still keeps using the startvalue.
#model UGT.UI.Web.MVC.Models.BelastingViewModel
<script language="JavaScript">
var config1 = liquidFillGaugeDefaultSettings();
#{
teller = 1;
string naam_var = null;
foreach (KeyValuePair<UGT.BL.Domain.BegrotingPackage.Categorie, double> cat in Model.Belasting)
{
naam = "fillgauge" + teller;
naam_var = "gauge" + teller;
#: var #naam_var = loadLiquidFillGauge("#naam", "#Html.DisplayFor(modelItem => cat.Value)", config1);
teller++;
}
}
function toonCirkels() {
#{
teller = 1;
naam = "fillgauge" + teller;
string naam_var2 = null;
foreach (KeyValuePair<UGT.BL.Domain.BegrotingPackage.Categorie, double> cat in Model.Belasting)
{
naam_var2 = "gauge" + teller;
// #: gauge1.update("#Html.DisplayFor(modelItem => cat.Value)");
// #: var #naam_var = loadLiquidFillGauge("#naam", "#Html.DisplayFor(modelItem => cat.Value)", config1);
// #: #naam_var2.update("#Html.DisplayFor(modelItem => cat.Value)");
teller++;
}
//#:gauge1.update("500");
}
}
public class BelastingsController : Controller
{
private BegrotingsManager begrotingsManager = new BegrotingsManager();
private int gemeenteId = 54;
private double loon = 200;
private BelastingViewModel belastingen = new BelastingViewModel();
// GET: Belastings
public ActionResult Index()
{
var belasting = begrotingsManager.GetBelastingGebruiker(this.loon, gemeenteId);
belastingen.Belasting = belasting;
UpdateModel(belastingen);
return View(belastingen);
}
[HttpPost]
public ActionResult Index(String loon)
{
this.loon = Double.Parse(loon);
var belasting = begrotingsManager.GetBelastingGebruiker(this.loon, gemeenteId);
belastingen.Belasting = belasting;
UpdateModel(belastingen);
return new HttpStatusCodeResult(HttpStatusCode.OK);
// return RedirectToAction("Index");
}
namespace UGT.UI.Web.MVC.Models
{
public class BelastingViewModel
{
public IDictionary<Categorie, double> Belasting { get; set; }
}
}
d3.selectAll('.range').on('change', function () {
this.value = parseInt(this.value);
if (this.value < 0) this.value = 0;
else if (this.value > 5000) this.value = 5000;
var loon = this.value;
var loonString = "€" + loon;
d3.select('.range_value').html(loonString);
sendLoon(loon, loonString);
});
}
function sendLoon(loon, loonString) {
$.ajax({
contentType: "application/json; charset=utf-8",
url: "/Belastings",
type: "POST",
data: JSON.stringify({ "loon": loon }),
success: function () {
// window.location.reload();
toonCirkels();
},
error: function () { }
});
}
The success of your Ajax call calls 'toonCirkels' which only contains razor generated code which is filled on page load. The content of this method never changes as it contains ONLY razor generated code and thus will always have the same logic with the same values.

Sending Arrays from View to Controller in MVC

I am trying to send the following values from view to controller
var ParamAliasArray = new Object();
for (var i = 1; i <= 1; i++) {
ParamAliasArray[i] = $("#txtParamAlias" + i).val();
}
var ParamValueArray = new Object();
for (var i = 1; i <= 4; i++)
{
ParamValueArray[i] = new Array();
for (var j = 1; j <= 1; j++) {
ParamValueArray[i][j] = $("#txtParamValue" + i).val();
}
}
one is 1D array and other is 2D array I am passing as
jQuery.ajaxSettings.traditional = true
$.ajax({
type: 'Post',
dataType: 'json',
url: 'Register/GetRegDataFromuser',
data: JSON.stringify({ GloabalAppID: GlobalAppID,
TransactionID: TransactionID,
OwnerID: OwnerID,
ParamAliasArray: ParamAliasArray,
ParamValueArray: ParamValueArray }),
contentType: 'application/json; charset=utf-8',
async: false,
success: function (data) {
console.debug(data);
},
error: function (data) {
console.debug(data);
}
});
I have written Action method as in
public ActionResult GetRegDataFromuser(int GloabalAppID, int TransactionID, string OwnerID, string[] ParamAliasArray, string[][] ParamValueArray)
{
---some logic--
}
So,I am not able to pass the array to the action method from View..Please help me out.
Thanks in advance.
you need to add ParamValueArray[i][j]=new Array(); this line.

Categories