Error in getting action parameter in MVC controller from javascript - javascript

I need to pass values from javascript to my controller action.
$.getJSON('/gallery/PublishImage', { imageid: itemsarray }, function (mydata) {
});
In javascript, it have a value. At the controller, it is null
public ActionResult PublishImage(string imageid)
{
var mydata = imageid;
return Json(mydata,JsonRequestBehavior.AllowGet);
}
how to resolve this.
my entire code is:
function publish() {
debugger;
var $trash = $("#trash li");
var itemsarray = [];
var lis = document.getElementById("trash").getElementsByTagName("li");
for (var i = 0; i < lis.length; i++) {
var item = lis[i].children[0].id;
itemsarray.push(item);
}
$.getJSON('#Url.Action("PublishImage")', { imageids: itemsarray }, function (mydata) {
});
in controller
public ActionResult PublishImage(string[] imageids)
{
var mydata = imageids;
return Json(mydata,JsonRequestBehavior.AllowGet);
}
for testig used string. but in the above code also return null.
is any thing am missed?

Given the name of this javascript variable I strongly suspect that itemsarray is not a string but some kind of javascript object (an array?). It must be string for this to work:
var itemsarray = 'foo bar';
$.getJSON('/gallery/PublishImage', { imageid: itemsarray }, function (mydata) {
});
If you want to send an array then you could do that:
var itemsarray = ['foo', 'bar', 'baz'];
$.getJSON('/gallery/PublishImage', { imageids: itemsarray }, function (mydata) {
});
and your controller action:
public ActionResult PublishImage(string[] imageids)
{
var mydata = imageids;
return Json(mydata, JsonRequestBehavior.AllowGet);
}

Related

JSON data to Array

This is my Javascript function that gets data from the HTML form.
$(function postProduct() {
$('#btn').click(function() {
var productName = document.getElementById("name").value;
var productDetail = document.getElementById("detail").value;
var productCategory = document.getElementById("category").value;
var dimensions = [productName, productDetail, productCategory];
var keys = $.map(dimensions, function(value, key) {
return value;
});
$.ajax({
type: "POST",
url: "api/product/addproduct",
data: keys,
success: function(result) {
alert('successful : ' + result);
return result;
},
error: function(error) {
alert("Not Working..");
}
});
}
});
});
This is my controller:
[HttpPost]
[Route("api/product/addproduct")]
public IActionResult AddProduct([FromBody] string[] addproduct)
{
var pProductName= addproduct[0];
var pProductDetail= addproduct[1];
var pProductCategory= addproduct[2];
Hotel NewProduct = new Product();
{
NewProduct.ProductName= pProductName;
NewProduct.ProductDetail= pProductDetail;
NewProduct.ProductCategory= pProductCategory;
}
_db.Products.Add(NewProduct);
_db.SaveChanges();
//create a new route for post method by id
return CreatedAtRoute(new { id = addproduct}, addproduct);
}
So, I'm trying to pass the inputted form and pass it to the controller by AJAX, However, it just fails.
This is the function that I use to make the json data to an array:
var dimensions = [productName, productDetail, productCategory];
var keys = $.map(dimensions, function(value, key) {
return value;
});
Or should I recode my controller for accepting json data. If so, please give me an example on doing it. Sorry, I'm new at web api.
UPDATE:
This is my jsondata:
productName: name
productDeatil: detail
productCategory:category
This is my Array:
keys:(7) ["name", "detail", "category"]
In your Ajax request, assign the data key to the following value...
{ productName: document.getElementById("name").value, productDetail: document.getElementById("detail").value, productCategory: document.getElementById("category").value }
This is a typical JSON formatted object.
You could then also remove your variable assignments and map function.
Finally you'd need to look into how to process this formatted JSON in your controller.
I'm unsure of how to go about this in asp.net-core-mvc but it could be something as simple as changing
var pProductName= addproduct[0];
to
var pProductName= addproduct.productName
Is the spacing between NewProduct and properties such as .ProductName intentional?
NewProduct .ProductName = pProductName;
Shouldn't it be like this?
Hotel NewProduct = new Product();
NewProduct.ProductName = pProductName;
NewProduct.ProductDetail = pProductDetail;
NewProduct.ProductCategory = pProductCategory;
With simplified object creation:
Hotel NewProduct = new Product() {
ProductName= pProductName,
ProductDetail= pProductDetail,
ProductCategory= pProductCategory
};
add data: JSON.stringifly(keys) in ajax solve the problem. Thank you for everyone's help!

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

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

How to read JSON Response from URL and use the keys and values inside Javascript (array inside array)

My Controller Function:
public function displayAction(Request $request)
{
$stat = $this->get("app_bundle.helper.display_helper");
$displayData = $stat->generateStat();
return new JsonResponse($displayData);
}
My JSON Response from URL is:
{"Total":[{"date":"2016-11-28","selfies":8},{"date":"2016-11-29","selfies":5}],"Shared":[{"date":"2016-11-28","shares":5},{"date":"2016-11-29","shares":2}]}
From this Response I want to pass the values to variables (selfie,shared) in javascript file like:
$(document).ready(function(){
var selfie = [
[(2016-11-28),8], [(2016-11-29),5]]
];
var shared = [
[(2016-11-28),5], [(2016-11-29),2]]
];
});
You can try like this.
First traverse the top object data and then traverse each property of the data which is an array.
var data = {"total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2},{"date":"2016-11-30","selfies":0},{"date":"2016-12-01","selfies":0},{"date":"2016-12-02","selfies":0},{"date":"2016-12-03","selfies":0},{"date":"2016-12-04","selfies":0}],"shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0},{"date":"2016-11-30","shares":0},{"date":"2016-12-01","shares":0},{"date":"2016-12-02","shares":0},{"date":"2016-12-03","shares":0},{"date":"2016-12-04","shares":0}]}
Object.keys(data).forEach(function(k){
var val = data[k];
val.forEach(function(element) {
console.log(element.date);
console.log(element.selfies != undefined ? element.selfies : element.shares );
});
});
Inside your callback use the following:
$.each(data.total, function(i, o){
console.log(o.selfies);
console.log(o.date);
// or do whatever you want here
})
Because you make the request using jetJSON the parameter data sent to the callback is already an object so you don't need to parse the response.
Try this :
var text ='{"Total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2}],"Shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0}]}';
var jsonObj = JSON.parse(text);
var objKeys = Object.keys(jsonObj);
for (var i in objKeys) {
var totalSharedObj = jsonObj[objKeys[i]];
if(objKeys[i] == 'Total') {
for (var j in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"selfies on "+totalSharedObj[j].date+":"+totalSharedObj[j].selfies+"<br>";
}
}
if(objKeys[i] == 'Shared') {
for (var k in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"shares on "+totalSharedObj[k].date+":"+totalSharedObj[k].shares+"<br>";
}
}
}
<div id="demo">
</div>
I did a lot of Research & took help from other users and could finally fix my problem. So thought of sharing my solution.
$.get( "Address for my JSON data", function( data ) {
var selfie =[];
$(data.Total).each(function(){
var tmp = [
this.date,
this.selfies
];
selfie.push(tmp);
});
var shared =[];
$(data.Shared).each(function(){
var tmp = [
this.date,
this.shares
];
shared.push(tmp);
});
});

Send single item of list from view to controller via AJAX

I have a view composed of a list of users:
#model List<LabelPrinting.Models.UserModel>
and I put these into a JavaScript object:
users = function () { return #Html.Raw(Json.Encode(Model)) }();
I then load a jQuery accordion with the values for each. I then choose to print avery labels for a particular user in the list and set a value. I'm trying to send only that particular user to the controller and am getting a null values for of the user properties:
function PrintAveryLabel(but) {
var id = but.id.substring(9);
var $rad = $(but).closest('tr').siblings().find('.radLabelOther');
if (($rad).is(':checked')) {
var $txtr = $rad.closest('tr').siblings().find('.classRows');
var $txtc = $rad.closest('tr').siblings().find('.classCols');
if ($txtr.val() === "0" || $txtc.val() === "0") {
$("#lblError").text("You have have not selected the rows and columns for the labels.");
$("#MessageDialog").dialog({ title: "Select Rows/Columns" });
$("#MessageDialog").dialog("open");
return false;
}
}
var data = findUser(id);
$.ajax({
type: 'POST',
data: { pat: data },
url: '#Url.Action("PrintUserLabels")'
});
}
The findUser function simply picks the entry in the list that matches the ID.
function findUser(id) {
var data;
for (i = 0; i < cnt; i++) {
if (users[i].UserId === parseInt(id)) {
data = users[i];
break;
}
}
return data;
}
My controller action:
[HttpPost]
public ActionResult PrintUserLabels(UserModel pat)
{
string retval = "";
if (pat.PrintLabel)
{
return RedirectToAction("Label", new { user = pat });
}
else
{
retval = "ERROR - you must make a selection";
Exception e = new Exception(retval);
HandleErrorInfo info = new HandleErrorInfo(e, "DYMO", "PrintPatientLabels");
return RedirectToAction("Error", info);
}
}
The label action is tried and true but I get a null user model. What am I doing wrong?

How to call and pass values to a controller method from jquery

I have a http controller which is called from a getJSON method. Its working pretty good. But now I want to do the same operation performed in handler in a controller method. I am sending a value through getJSON to handler and it perform with that value.
Here is my getJSON
$(document).ready(function () {
$.getJSON('ProfileHandler.ashx', { 'ProfileName': 'Profile 1' }, function (data) {
$.each(data, function (k, v) {
alert(v.Attribute+' : '+v.Value);
});
});
});
and here is my handler
public void ProcessRequest(HttpContext context)
{
try
{
string strURL = HttpContext.Current.Request.Url.Host.ToLower();
//string ProfileName = context.Request.QueryString["profilename"];
string strProfileName = context.Request["ProfileName"];
GetProfileDataService GetProfileDataService = new BokingEngine.MasterDataService.GetProfileDataService();
IEnumerable<ProfileData> ProfileDetails = GetProfileDataService.GetList(new ProfileSearchCriteria { Name = strProfileName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string strSerProfileDetails = javaScriptSerializer.Serialize(ProfileDetails);
context.Response.ContentType = "text/json";
context.Response.Write(strSerProfileDetails);
}
catch
{
}
}
how can I call and pass 'ProfileName' to a controller method ?
Your code is correct and you should be able to retrieve the ProfileName with the following:
string strProfileName = context.Request["ProfileName"];
And if you wanted to pass it to a controller action simply define this action:
public ActionResult SomeAction(string profileName)
{
var profileDataService = new BokingEngine.MasterDataService.GetProfileDataService();
var request = new ProfileSearchCriteria { Name = profileName };
var profileDetails = profileDataService.GetList(request);
return Json(profileDetails, JsonRequestBehavior.AllowGet);
}
and then invoke your controller action with AJAX:
<scirpt type="text/javascript">
$(document).ready(function () {
var url = '#Url.Action("SomeAction")';
$.getJSON(url, { profileName: 'Profile 1' }, function (data) {
$.each(data, function (k, v) {
alert(v.Attribute + ' : ' + v.Value);
});
});
});
</script>
You almost have it. Here is an example:
Javascript
function someFunction(e) {
$.post("#Url.Action("MethodName", "ControllerName")", { ParameterName: e.value }, function(data) {
$("#someDiv").html = data;
});
}
C# Controller
[HttpPost]
public ActionResult MethodName(string ParameterName)
{
return "Hello " + ParameterName;
}
If you passed in your name to the JavaScript function "someFunction", the controller would return "Hello [your name]". Help?

Categories

Resources