Accessing of Web API response object in another partial view (cshtml / cshtml.cs file) in Visual Studio 2022 - ajax

On click of a button will from a partialview 1 below js function will be called and get the data from the controller and will be redirected to another partialview. Since it the controller is in another project and hosted separately, controller is not returning the partialview hence I am redirecting it if the ajax call is success.
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(paramObj),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (response) {
var userObject = response.internalObject;
window.location.href = url2;
},
error: function (response, status, error) {
if (response.responseText != undefined) {
const obj = JSON.parse(response.responseText);
fnShowMessage(obj.DisplayMessage);
}
}
});
I have the data in "userObject" from the ajax call which needs to be displayed in partialview, but I cannot access it or not sure how to access it.
The assigned value in OnGet() method in "partialview2.cshtml.cs" is able to retain in "partialview2.cshtml" file. But how to get the values which I got from the ajax call in partialview 1 in code behind of partialview 2.
public class UserModel : PageModel
{
[BindProperty]
public UserObject UserObject { get; set; } = new();
public void OnGet()
{
UserObject.UserName = "man";
}
}

You can try to return JsonResult in OnGet:
ajax:
$.ajax({
type: "POST",
url: "/Home/Test",
data: JSON.stringify(paramObj),
contentType: "application/json; charset=utf-8",
traditional: true,
dataType: "json",
success: function (response) {
var userObject = response;
window.location.href = url2;
},
error: function (response, status, error) {
if (response.responseText != undefined) {
const obj = JSON.parse(response.responseText);
fnShowMessage(obj.DisplayMessage);
}
}
});
OnGet handler:
public class UserModel : PageModel
{
[BindProperty]
public UserObject UserObject { get; set; } = new();
public JsonResult OnGet()
{
UserObject.UserName = "man";
return new JsonResult(UserObject);
}
}

Related

Ajax post zero to controller

I'm trying to POST an int with Ajax to my controller
Js
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity",
type: "POST",
data: { id: provinceId },
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
code in my controller :
[HttpPost]
public ActionResult FillCity(int id)
{
var cities = _context.City.Where(c => c.ProvinceId == 5);
return Json(cities);
}
but it always post 0 as id, I tried digits instead of provinceId, but it rtills send 0
You should create an class that have a Id Property.
public class ProvinceIdDto
{
public int Id { get; set; }
}
replace int id with ProvinceIdDto model in action
[HttpPost]
public ActionResult FillCity(ProvinceIdDto model)
{
var cities = _context.City.Where(c => c.ProvinceId == model.Id);
return Json(cities);
}
replace { id: provinceId } with JSON.stringify({ Id: provinceId }),
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity",
type: "POST",
data: JSON.stringify({ Id: provinceId }),
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
Another options is you can replace HttpPost method with HttpGet and pass id to action like this.
Change type: "POST", to type: "GET",
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity?id="+provinceId,//<-- NOTE THIS
type: "GET",//<-- NOTE THIS
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
C#
[HttpGet]
public ActionResult FillCity(int id)
{
var cities = _context.City.Where(c => c.ProvinceId == id);
return Json(cities);
}
when you do { id: provinceId } you are creating an object with property id
in your controller you are just expecting an id. You will need to ether:
A pass it as a query parameter url: "FillCity?id=" + provinceId
B create an object to be parsed from the request body.
public class Payload {
public int Id {get;set;}
}
and use it like this
public ActionResult FillCity([FromBody] Payload payload)
Can you verify this statement has a value:
var provinceId = $(provinces).val();
It's possible that isn't finding what you are looking for, and because you have the type int as a parameter, it defaults it to "0".
You shouldn't need to change it to a GET and your MVC method is fine as is. You can see from JQuery's own sample it should work:
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
I think it might not be finding the input field successfully.

How to pass Ajax Json object to the Controller Class in .Net Core?

We are trying to make a Ajax request to our Core Web API and get the data Json result back to the Controller for further processing, Which include Deserialization of the Json object result, Ajax request is working fine and we are able to get the required Json data in data.
Can anyone here please advise the changes or the alternatives to achieve this?
View (Ajax Request)
#section scripts
{
<script type="text/javascript">
$(document).ready(function () {
GetEventDetails('#Url.Content("~/")');
});
function GetEventDetails(contextRoot) {
$.ajax({
type: "GET",
url: contextRoot + "api/EventsAPI",
dataType: "json",
success: function (data) {
debugger;
var datavalue = data;
contentType: "application/json";
//Send data to controller ???
console.log(data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
</script>
}
Controller.cs
public ActionResult Index()
{
/*Do all stuff before returning view
1. Get Json Data from Ajax request
2. Deserialize the obtained Json Data
3. return to view
*/
return View("Index");
}
Update:
I have tried the solution given by #J. Doe, but still unable to get the result set. Please check the screenshot and below code..
Ajax Request:
function GetEventDetails(contextRoot) {
$.ajax({
type: "GET",
url: contextRoot + "api/EventsAPI",
dataType: "json",
success: function (data) {
debugger;
var datavalue = data;
contentType: "application/json; charset=utf-8";
console.log(data);
var EventJson = data;
console.log(EventJson);
$.ajax({
type: "POST",
url: "#Url.Action("Index")",
dataType: "json",
data: EventJson,
contentType: "application/json; charset=utf-8",
//data: EventJson,
success: function (data) {
alert(data.responseText);
console.log('Data received: ');
console.log(data.responseText);
},
failure: function (errMsg) {
console.log(errMsg);
}
});
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
Class Properties:
public class RootObject
{
public Embedded _embedded { get; set; }
public Links _links { get; set; }
public Page page { get; set; }
}
Here is Action Result Controller:
public ActionResult Index(RootObject model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
//return View("Index");
}
Error Snapshot:
enter image description here
1) Add [FromBody] the controller you are returning to. This will make the controller expect a JSON object.
[HttpPost]
public ActionResult Index([FromBody]RootObject model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
//return View("Index");
}
2) If this doesn't work you are not posting a correct json object/you are not posting a json object use console.dir(EventJson); to inspect the object you are passing in the console of the browser.
3) How to create a JSON object in JS: https://www.w3schools.com/js/js_json_stringify.asp
We are trying
Hello soviet sojuz!
But back to question - A 2 months ago i created sample on GitHub with ajax with .Net Core - https://github.com/CShepartd/ASP.Net_Core_-_Ajax_Example
In short:
Make action with objects in controller:
public IActionResult Ajax(string name1, string name2)
{
return View();
}
Next in view send name1 and name2 to action
$('form').submit(function(event) {
event.preventDefault();
var data = {
name1: $("input[name='name1']", this).val(),
name2: $("input[name='name2']",this).val()
};
$.ajax({
type: 'POST',
url: '/Home/Ajax',
dataType: 'json',
data: data,
success: function(response) {
alert(response);
console.log('Data received: ');
console.log(response);
},
failure: function(response) {
//...
},
error: function(response) {
//...
}
});
});

Not getting Json object (having a collection) correctly in controller using ajax call

I am sending a json object to controller via ajax call, data property of ajax call showing correct data. On post to controller's method -received parameter having collection and its count is showing perfectly but the properties inside the collection is not showing values.
Here is the code -
Controller-
[HttpPost]
public ActionResult ImageOperations(ImageProcessingModel imageProcessingModel)
{
return Json("sucess");
}
Model-
public class ImageProcessingModel
{
public string Source { get; set; }
private List<ThumbnailImageSubTaskModel> _thumbnailImageSubTaskModel;
public List<ThumbnailImageSubTaskModel> ThumbnailImageSubTaskModel
{
get
{
if (_thumbnailImageSubTaskModel == null)
{
_thumbnailImageSubTaskModel = new List<ThumbnailImageSubTaskModel>();
}
return _thumbnailImageSubTaskModel;
}
}
}
js-
var ImageProcessingModel =
{
"Source": "test",
"ThumbnailImageSubTaskModel":allThumbnails.allItems()
}
allThumnails.allItems is ko.observableArray() which having values.
$.ajax({
url: '/ImageProcessingTask/ImageOperations',
type: 'Post',
data: ImageProcessingModel,
success: function (data, status) {
processEscapeKeyPress = true;
var fn = window[successCallback];
fn(data, passDataToCallback);
},
error: function (xhr, desc, err) {
alert(err);
processEscapeKeyPress = true;
processAjaxError(xhr, desc, err);
},
});
here ImageProcessingModel having all values and source is simple a string so this value is coming in the controller only the ThumbnailImageSubTaskModel showing counts but not its value.
Thanks!!
A common problem encoutered with sending JSON through AJAX to MVC. Many forget to set the type of data in their AJAX request.
Try setting the datatype and contentType:
$.ajax({
url: '/ImageProcessingTask/ImageOperations',
type: 'Post',
**contentType: 'application/json; charset=UTF-8',
dataType: 'json',**
data: ImageProcessingModel,
success: function (data, status) {
processEscapeKeyPress = true;
var fn = window[successCallback];
fn(data, passDataToCallback);
},
error: function (xhr, desc, err) {
alert(err);
processEscapeKeyPress = true;
processAjaxError(xhr, desc, err);
},
});

To what mvc object do I bind this kind of javascript array?

I am populating an array with an [int,bool]:
$.each(ownedChecked, function (key, val) {
/*code to set id as int and paintedTrue as bool*/
ownedIDs.push([id,paintedTrue]);
});
I create a var that will be stringified:
var saveData = { OwnedListEntryIDs:ownedIDs };
//send data
$.ajax({
url: '/ListEntry/OwnedModels',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(saveData),
success: function (data) { alert('Update success: ' + data); },
failure: function (data) { alert('Update failed: ' + data); }
});
Here is the ViewModel:
public class OwnedPaintedSave
{
//collection contains a ListEntryID and a bool indicating whether it is painted or not
public Dictionary<int,bool> OwnedListEntryIDs { get; set; }
}
Once in the controller method, ModelState.Isvalid passes and code gets to the foreach loop, but models is always NULL:
[HttpPost]
public JsonResult OwnedModels(OwnedPaintedSave models)
{
if (ModelState.IsValid)
{
foreach (var id in models.OwnedListEntryIDs)
{ }
}
}
I tried setting traditional:true in the $.ajax method, but same issue. I'm guessing the Dictionary in the ViewModel is not what I need to bind to, but I'm not sure what it should be. Thanks for any help.
I gave the OwnedPaintedSave object two int[] properties, one for OwnedIDs and one for PaintedIDs.
I think the problem lies in your controller. You are passing var saveData = { OwnedListEntryIDs:ownedIDs }; (essentially a Dictionary<int, bool> - yes?) as your data but the parameter in the action result is of type OwnedPaintedSave
I think if you change your controller parameter to Dictionary<int, bool> ownedListEntryIDs and don't stringify the javascript object, the framework is clever enough to serialize and deserialize your object. So you would have this...
var saveData = { OwnedListEntryIDs:ownedIDs };
//send data
$.ajax({
url: '/ListEntry/OwnedModels',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: saveData,
success: function (data) { alert('Update success: ' + data); },
failure: function (data) { alert('Update failed: ' + data); }
});
And then this in your controller...
[HttpPost]
public JsonResult OwnedModels(Dictionary<int, bool> ownedListEntryIDs)
{
if (ModelState.IsValid)
{
foreach (var id in ownedListEntryIDs)
{ }
}
}

Pass serialized form to Action and bind to model

I am trying to bind model received from Ajax call but that do not work. Maybe someone could help me?
I am calling ValidateFile Action using Ajax
$.ajax({
url: '#Url.Action("ValidateFile", "Converter")',
data: ({ file: fileName, formData: serializedForm }),
type: 'POST',
success: function (response) {
if (response.result) {
} else {
RemoveFile(fileName);
}
}
});
The Fiddler show such query
file=!!!SP+Design!!!.txt&formData%5BEmail%5D=tomas%40mydomain.com
I receive data in my Action with file parameter populated but formData.Email property is always Null
[HttpPost]
public JsonResult ValidateFile(string file, UploadOptionModel formData)
{
}
My UploadOptionModel model
namespace PC.Models
{
public class UploadOptionModel
{
public string Email { get; set; }
}
}
Form which I am trying to serialize
#model PC.Models.UploadOptionModel
#using (Html.BeginForm())
{
#Html.EditorFor(p => p.Email)
}
JS Serialization function
function serializeForm() {
var data = $("form").serializeArray();
var formData = {};
for (var i = 0; i < data.length; i++) {
formData[data[i].name] = data[i].value;
}
return formData;
}
You need to JSON encode the data and set the content type to JSON for the model binder to work with JSON. So try this:
$.ajax({
url: '#Url.Action("ValidateFile", "Converter")',
data: JSON.stringify({ file: fileName, formData: serializedForm }),
contentType: 'application/json',
type: 'POST',
success: function (response) {
if (response.result) {
} else {
RemoveFile(fileName);
}
}
});

Resources