I have this jquery ajax get method on an Index razor in my application:
$.ajax({
url: "#Url.Action("SubmitProjectForPreapproval", "api/Project")",
type: "GET",
cache: false,
data: { projectId: "#ViewContext.RouteData.Values["ProjectId"]" }
}).done(function (data) {
var count = 0;
$.each(data, function (index, value) {
$("#ulMessages").append("<li>" + value + "</li>");
count++;
});
// Assume validation errors if more than 1 message
if (count > 1) {
$("#btnSubmit").removeAttr("disabled");
}
}).fail(function () {
$("#ulMessages").append("<li>An error occurred. Please try again later</li>");
$("#btnSubmit").removeAttr("disabled");
}).always(function () {
$("#imgAjaxLoader").hide();
});
This calls a method within the api/project controller that returns a list of strings:
[HttpGet]
public List<string> SubmitProjectForPreapproval(int projectId)
{ ... }
What I want to do is convert this to an ajax post method. I've been struggling to do just that for the better part of the day. My question is, what is everything that needs to change in order for this to happen? e.g. - change attribute of the method to [HttpPost], and how do I send it the route value? (int pojectId)
Edit: If I do this it works for some reason:
public List<string> SubmitProjectForPreapproval(/*int projectId*/)
{
int projectId = 3308;
...
}
Not sure why it doesn't find my method if I have the parameter there.
I'm not sure how the #Url stuff formats with your system - but just changing it to something like:
$.ajax({
url: "#Url.Action("SubmitProjectForPreapproval", "api/Project")",
type: "POST",
cache: false,
data: { projectId: "#ViewContext.RouteData.Values["ProjectId"]" }
}).done(function (data) {
If you're bit:
#Url.Action("SubmitProjectForPreapproval
..actually has any ?xxx values in it, you also need to add them into the data: { ... }
The problem was indeed the way I was sending the data to the controller action. I fixed it by doing the following:
Alter the ajax method (make use of JSON.stringify):
var projectIdObject = {
ProjectId: "#ViewContext.RouteData.Values["ProjectId"]",
}
$.ajax({
url: "#Url.Action("SubmitProjectForPreapproval", "api/Project")",
type: "POST",
cache: false,
data: JSON.stringify(projectIdObject),
contentType: 'application/json',
}).done(function (data) { ... }
Add a class to take this stringified value:
public class ProjectIdObject
{
public string ProjectId { get; set; }
}
Alter the controller action method to receive this new object and extract the value I want:
[HttpPost]
public List<string> SubmitProjectForPreapproval(ProjectIdObject projectIdObject)
{
int projectId = int.Parse(projectIdObject.ProjectId);
...
}
Related
I have JavaScript function where I have an array and when I send that array to my C# controller, it should be in such way way that my controller should understand.
JavaScript function
function Check(obj) {
var eArray = $('..').map(function () {
return this.getAttribute("value");
}).get();
$.ajax({
url: "/Order/Check",
data: { GUID: JSON.stringify(eArray) },
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
});
My Controller
public ActionResult Check()
{
string guid = HttpContext.Request["GUID"];
var result = //send the result
return Json(result, JsonRequestBehavior.AllowGet);
}
I would like to get an array in my controller.
I'm not really sure what you are trying to achieve. From what I saw in your comments, you are sending an array of GUIDs to your controller, but that results in it being send as a string, and you want an array.
I tested your code and modified it a bit:
$.ajax({
type: "POST",
url: /your url/,
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
data: JSON.stringify({GUID: eArray}),
});
Where eArray is let eArray = ['D5FAF478-CF43-40E1-BE79-BB90147A3194', '2E79B23E-D264-4901-A065-7E0B7032A5D8']
Then, in my controller, I receive it as a model:
public class Dto
{
public string[] GUID { get; set; }
}
Then, you can use it like this:
[HttpPost]
public IActionResult Post([FromBody] Dto dto)
{
var listOfGuids = dto.GUID.Select(guid => Guid.Parse(guid)).ToList();
var result = Services.CheckRecords(listOfGuids);
...
}
It seems that unfortunately the standard JavaScriptSerializer.Deserialize doesn't handle Guid type.
Therefore, I would go with something like
public ActionResult Check()
{
string guidsStr = HttpContext.Request["GUID"];
var guids = new List<Guid>();
foreach (var guid in Regex.Replace(guidsStr, "[\\[\\\"\\]]", "").Split(",")) {
Guid newGuid;
if (Guid.TryParse(guid, out newGuid)) {
guids.Add(newGuid);
} else {
// handle invalid guide value
}
}
// guids list now contains parsed Guid objects
// do here what you need to do with the list of guids
return Json(result, JsonRequestBehavior.AllowGet);
}
Please let me know if this helps.
Is it possible to pass the form data with out using FormData by using the JavaScript Model. As my form has many controls I would like to go with Model approach instead of FormData.
Is there a way to pass selected files to controller with out using HttpPostedFileBase? I have nearly 10 different class which accepts HttpPostedFileBase
I have a class as follows in c#
public class ArtGallery{
Public string GallerName {get;set;}
Public HttpPostedFileBase[] Documents {get;set;}
}
The equivalent JavaScript Model is
class ArtGallery{
GallerName;
Documents[];
}
On my save of the form here is how I am doing it
function saveFormData(){
let gallery = new ArtGallery();
gallery.GallerName = "Test";
$.each($("input[type=file]"), function (i, obj) {
$.each(obj.files, function (j, file) {
gallery.Documents.push(file);
});
});
saveToDb();
}
function saveToDb() {
let url = "/MyController/PostData/";
$.ajax({
url: url,
type: 'POST',
async: false,
data: '{gallery : ' + JSON.stringify(gallery) + '}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
},
error: function (request) {
}
});
}
My controller is as follows, which is getting triggered but documents I am unable to get
[HttpPost]
public JsonResult PostUserData(ArtGallery gallery) {
}
Ajax call works but the passed object is empty.
Its a simple setup of passing a cart object to a controller action.
The call happens but man is empty when it hits the Action.
The paylod being sent(in chrome) is:
{"man":"testtext2"}
The response is:
{"man":null}
.net cartitem:
public class Cartitem
{
public string man { get; set; }
}
Javascript cartitem:
class cartitem {
constructor( _man, ) {
this.man = _man;
}
}
Controller Action:
[HttpPost]
public ActionResult AddToCart(Cartitem myCartitem)
{
//ERROR: cartitem values are coming in empty
return Json(myCartitem);
}
Javascript
$(".AddLink").click(function () {
var json = JSON.stringify(c);
var cartitem = JSON.stringify({
'man': 'testtext2',
});
$.ajax({
type: "POST",
url: '#Url.Action("AddToCart", "ShoppingCart")',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: cartitem,
success: function (data) {
alert("Data Back: " + data.man);
}
});
});
Edit
To remove a a lot of red hearings, I've simplified the code so its one single string(man).
The result is the same, MyCartitem is coming in empty.
Add [FromBody] to the Action method e.g
public ActionResult AddToCart([FromBody] Cartitem myCartitem)
{
}
2 days lost!
My controller:
[HttpPost]
public IActionResult UserRoleChanged(string roleName,string userName)
{
var a = roleName;
var b = userName;
return RedirectToAction("UserManager");
}
Script in view:
if (window.confirm('Are you sure that you want to change role?')) {
jQuery.ajax({
type: "POST",
url: "#Url.Action("UserRoleChanged", "DashBoard")",
dataType: 'json',
data: { 'roleName': this.text, 'userName': 'SomeName'},
cache: false,
success: function (data){
window.location.href = data;
},
failure: function (data) {
}
})};
When I run script above UserRoleChanged action does not invoke. If I try to remove userName variable from data in ajax then UserRoleChanged action method invokes without any problem. How can i pass multiple data to my controller? What is wrong with my code?
Remove the dataType: 'json' from the ajax, and try again. As you are trying to get the values on server side as normal variable, so dataType: 'json' is not required here.
You can create a model with same properties and pass it as a parameter. Its a good practice.
Looks like this.
public class User
{
public string RoleName { get; set; }
public string UserName { get; set; }
}
And the json looks like this example
{
"RoleName" : "somename",
"UserName" : "somename"
}
I'm working on an ASP.NET MVC 4 website and I've got some troubles with a functionality. I explain, I've to select entities displayed in a table with their linked checkbox :
Screenshot of my table where each row has a checkbox with the same Id as the entity
Console showing updates in the array
Inside my script I have been abled to store each checked Id's checkbox in an array and remove those if the checkbox is unchecked. But I can't pass the array to my controller's function to delete each selected entity in the database.
I used $.ajax() from jquery to send through a POST request the array (as JSON) but I always get 500 error :
JSON primitive invalid
Null reference
Here's my function in my script (I don't know if my array's format is valid) :
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: JSON.stringify(docsArray),
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ' + result.d);
},
error: function (result) {
alert('Fail ' + result.d);
}
});
}
Then, the POST call the following function in my controller :
[Authorize]
[WebMethod]
public void DeleteDocuments(string docsToDelete)
{
int id;
string[] arrayDocs = JsonConvert.DeserializeObject<string[]>(docsToDelete);
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
}
Update 2
[Authorize]
public ActionResult DeleteDocuments(int[] docsToDelete)
{
try{
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return Json("Success");
}
catch
{
return Json("Error");
}
}
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: docsArray,
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ' + result.d);
},
error: function (result) {
alert('Fail ' + result.d);
}
});
}
Any ideas about this issue ? I hoped I was clear enough. Do not hesitate if you need more details.
If you are passing an integer array properly from $.ajax (i.e. your docsArray should be having value like [15,18,25,30,42,49]) then you should try :
[Authorize]
public ActionResult DeleteDocuments(int[] docsArray)
{
//int id;
//string[] arrayDocs = JsonConvert.DeserializeObject<string[]>(docsToDelete);
try {
foreach (int docId in docsArray)
{
//int.TryParse(docId, out id);
dal.DeleteDocument(docId); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return "Success ";
}
catch {
return "Error";
}
}
Update :
Your javascript code should be :
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: JSON.stringify(docsArray),
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ');
},
error: function (result) {
alert('Fail ');
}
});
}
Maybe the datatype in the JSON array is not a string? (This could happen if you have an array in the form of [45,64,34,6], or a mixed one like [345,"wef4"]).
To make sure something is a string in Javascript you can do this: var string = "".concat(otherVar);
Try changing your ajax data to something like this..
data : JSON.stringify({'docsToDelete':docsArray}),
Make these changes to your code.
In Jquery
data: docsArray, no need to stringify the array
In Controller
[Authorize] //remove [WebMethod]
public ActionResult DeleteDocuments(string[] docsToDelete) //Add ActionResult, Change parameter to accept array
{
int id;
string[] arrayDocs = docsToDelete; //no need of deserilization
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return Json(id); //return id back to ajax call...
}