Why does an empty string come to the controller instead of null? - c#

There is the following controller:
public JsonResult Report(string tt = null)
{
//some code
}
and ajax request
$.ajax({
type: "POST",
url: '#Url.Action(nameof(ManageController.Report))',
data: {
"tt": $('#ServiceFilter').val(),
},
success: function () { }
})
ServiceFilter in this case has a null value, but an empty string comes to the controller, why?

Because $('#ServiceFilter').val() has not a null value in JavaScript.
If you run your application, and open the console (F12, or inspect), and you use this command: $('#ServiceFilter').val()
You will see one of two things.
Or $('#ServiceFilter') does not exist, and has undefined value, or it exists and has a '' value (String.empty).
And in your controller, the line public JsonResult Report(string tt = null)
means that if that method is not receiving any parameter, it will set it null, but in this case, is receiving an empty value

Related

How to fetch Session variable value from a controller to ajax call in c# asp.net mvc

I want to fetch Session variable value from an mvc controller actionresult which returns a cshtml view. This ajax call is connected in a button click and is calling from a different cshtml.
function accountLogin() {
$.ajax({
url: accountLogin,
async: true,
type: 'POST',
cache: false,
success: function (data) {
var testUser = #Session[Keys.accountrole];
alert(testUser);
$("#navigationbar").empty();
$("#navigationbar").html(data);}
C# Code
[HttpPost]
public ActionResult accountLogin(){
Session[Keys.accountrole] = "value";
return View("_viewpage");
}
The curent implementation is reaturning either undefined session variable or it will display the #session keyword itself not the value in it.
You can only access Session on the server side. So you have to get a Session variable value inside of the action and retun it back as a json value
Try this
[HttpPost]
public IActionResult accountLogin(){
//I don't understand why you need it
Session[Keys.accountrole] = "value";
var sessionAccountRole=Session[Keys.accountrole];
return OK( {accountRole=sessionAccountRole} );
// or if you use an ancient net
return Json ( new {accountRole=sessionAccountRole} );
// or maybe
return new JsonResult {accountRole=sessionAccountRole};
}
and ajax
success: function (data) {
var testUser = data.accountRole;
alert(testUser);

Jquery .post method is sending a null value. How to pass actual value to controller?

I have a controller that applies to an edit view in asp.net MVC. I have an actionlink that sends the row Id to the controller which then brings back the correct row to see in the associated view.
I then have a partial view below that. That also requires a parameter in order to bring associated data from another table.
I have a Jquery .post call that runs after the page is loaded. I can alert out and show the exact value I want to send to the controller.
$(document).ready(function () {
var url = "/Home/MmsAndNotes";
var Uc = $("#Id").serialize();
alert(Uc);
$.post(url, {Id: Uc}, function (data) {
alert("what is Uc now? " + uc); //just for testing
});
})
I have also used it this way.
$(document).ready(function () {
var url = "/Home/MmsAndNotes";
var Uc = $("#Id").val();
alert(Uc);
$.post(url, Uc, function (data) {
});
})
the alerts come up and show the value I want. However, when the .post call runs, it sends a null value. Here is my controller.
public ActionResult MmsAndNotes(string Id)
{
//Declare LogisticsVM for individual policy info
LogisticsMMS_NotesVM model;
if(uc == null)
{
return Content("uc is empty.");
}
int val = Convert.ToInt32(uc);
using (Db db = new Db())
{
LogisticsMMS_NotesDTO dto = db.LogisticsMMS.Find(val);
//confirm policy exists
if (dto == null)
{
return Content("This policy cannot be found." + val);
}
model = new LogisticsMMS_NotesVM(dto);
}
return PartialView(model);
}
It always returns as uc is empty. I repeat, when the alerts come up. I get the correct value to send to the controller. But once it sends, something happens and it converts to null. HELPPPPP.. please .. I'm losing my mind over this one.
I don't know why, but changing my $.post() call to an $.ajax({}) call solved the issue. As you can see above, I had the $.post call. Using this instead,
$.ajax({
type: "POST",
url: "/Home/MmsAndNotes",
dataType: 'text',
data: { Id: Uc }
});
Solved it. I thought Jquery's shortened calls worked the same way. They certainly might, but doing it this way was the only way it worked for me.
P.S. Thanks Tyler (above) for your comments.
this solution should be work :
$(document).ready(function () {
$.ajax({
url: '/Home/MmsAndNotes',
type: 'GET',
dataType: "html",
data: { uc : $("#Id").val() },
success: function (result) {
code here
}
});
})
You need to verify if $("#Id").val() is not empty

mvc controller pameter getting null value in ajax call

I am making ajax call like this
deleteAge(item: any): string {
$.ajax({
method: "POST",
url: 'DeleteAge',
data: item.Id(),
success: (response) => {
toastr.success("ready soon");
},
error: (event) => {
toastr.error("Error occured ");
}
}).always(() => {
});
return "";
}
Here is my method in controller which is currently nothing almost implemented
[HttpPost]
public ActionResult DeleteAge(string id)
{
throw new Exception();
}
when i run the code then in my controller i dont get any id.. its null. when i debug my javascript code then this code item.Id() is not blank. Even if i pass hardcoded value to data in ajax call still controller gets null. What is wrong?
Rather than using:
data: item.Id(),
I'd suggest using:
data: { id: item.Id()},
This way the id value is associated with the id name - allowing model binding to work correctly.
Pass parameters like json format in ajax
replace data: item.Id() with data: {id: 1}

Can't pass serialized Json to Web API action

NOTE Please see the update at the bottom.
I'm picking up maintenance on an existing (working) application.
The application receives data into a class via a post to a Web API controller action.
However when I try to test this by posting it some data it just gives an empty object.
I assumed that my Json must be wrong so I tried sending the Json string as text and deserializing manually, and this works fine, returning the populated object I would expect to see.
I've searched online and seen various suggestions about adding attributes to the parameters but this doesn't do it for me.
The code looks pretty much as follows:
[HttpPost]
[AllowBasicAuthentication]
public async Task<MyResponse> ProcessData(
[FromUri]string key,
[FromUri]string name,
[FromUri]string value1,
[FromBody] DataClass value // this is never populated
)
{
// the following returns the data as expected
var test = new JavaScriptSerializer().Deserialize<DataClass>(value1);
...
}
The jQuery I'm using to test this is as follows:
$('#post').click(function () {
var key = $('#key').val();
var name = $('#name').val();
var value1 = $('#value').text();
var value = JSON.parse(value1);
var url = '/api/ProcessData/?key=' + key
+ '&name=' + name
+ '&value1=' + value1
/* with this post value appears in action as an instantiated but empty object */
$.post(url, { value: value })
.success(function (r) {
...
})
.fail(function (r) {
...
})
/* also tried the following, but value appears as null object
$.ajax({
url: url,
type: 'POST',
cache: false,
contentType: "application/json",
data: value,
success: function (r) {
alert(r);
}
});
*/
});
[EDIT]
Just to clarify, I added the value1 string parameter to test that the Json can be deserialized correctly, which it can, so the Json is ok and the class is ok.
UPDATE
This works when called from Postman so the error must be in the jQuery.
Can anyone show the correct way to do this?
Thanks
[/EDIT]

$.ajax and C# MVC Controller returns error or nothing

I have an AJAX JS functions which calls a C# MVC HttpPost Controller. This will return an object but for the purposes of debugging I am just trying to return a string.
JS AJAX code:
function UpdateBlogFilters(month, year) {
var url = "/HttpPost/GetBlogPostsPerMonth";
if (month != null && month != "" && year != null && year != "") {
alert(month + " " + year);
$.ajax({
url: url,
data: { monthValue: month, yearValue: year },
cache: false,
type: "POST",
success: function (data) {
console.log("Data " + data);
var markup = "";
},
error: function (response) {
console.log(response.responseText);
console.log("Error: " + response);
}
});
console.log("1");
}
console.log("2");
}
Controller Code:
[HttpPost]
public ActionResult GetBlogPostsPerMonth(int monthValue, int yearValue)
{
.... the non-debug code
return Json("test");
}
This is returning an error, but the responseText and any error information is blank? I have verified that the controller is being called and it is reaching the return statement in the C# without error.
Any help?
Change your C# code to read something like this:
[HttpPost]
public ActionResult GetBlogPostsPerMonth(int monthValue, int yearValue)
{
.... the non-debug code
return Json(new { result = "test" });
}
Ultimately, you want to pass an object into Json(). You can pass an instance of a class, or an anonymous type, or dynamic.
This was the solution. The AJAX call in itself worked fine. All code posted here was correct as per Bhavik.
The issue was that this AJAX request was called onclick of a hyperlink and this hyperlink although having no href set, was refreshing the page and somehow cancelling off the AJAX request. Removing the href to leave
<a onclick="UpdateBlogFilters(5,2014)">
resulted in the object being returned from AJAX successfully.
Why do you have "/HttpPost/" in url? Is that name of a controller that is different from the one you are using to render the view? Can you try without /HttpPost/
var url = "GetBlogPostsPerMonth";

Categories