HttpPostedFileBase null on controller / ajax resquest - ajax

I'm trying to upload a file and send it to controller, but it's always returning null. Here's the code:
[HttpPost, ValidateAntiForgeryToken]
public JsonResult Edita(string nome, string login, string email, string dataNascimento, HttpPostedFileBase avatar)
{
if (ModelState.IsValid)
{
......
}
}
Here's the javascript code.... am i missing anything? I've tried with formData as well, but couldn't make it work
$(document).ready(function () {
$("#btnSalvar").click(() => {
if (form.valid()) {
var url = "#Url.Action("Edita", "Usuario")";
let myFormData = $("#formUsuario").serializeArray();
$.ajax(
{
type: "POST",
url: url,
data: myFormData,
dataType: 'json',
autoUpload: true,
success: function (data) {
if (data.status == "OK") {
$("#userModal").modal("hide");
}
}
});
}
});
});

I found out the solution for this issue. My had the #Html.AntiForgeryToken() validation, so i removed it and it worked!

Related

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

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);
}
}

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) {
//...
}
});
});

Pass action with model to jquery ajax success call

My Jquery Ajax Call. How to return model from action to ajax and pass to another action.
function ChangeName(id)
{
var name=$("#name").val();
$.ajax({
cache:false,
url: "#Url.Action("EditName", "Order")",
data: "Name=" +name+"&Id="+id ,
type: "POST",
success: function (data) {
window.location.href=data.Url;//doesnt work passes null model
}
});
}
public ActionResult EditName(string name,int id)
{
var product= GetProduct(id);
product.Name=name;
UpdateProduct(product);
var model=new ProdModel(){id=id};
return Json(new
{
Url = Url.Action("Test","Order",new{model=model})
},JsonRequestBehavior.AllowGet);
}
public ActionResult Test(ProdModel model)//Model null
{
return RedirectToAction("List", "Product");
}
I have tried this but not getting success.
Try this
function ChangeName(id)
{
var name=$("#name").val();
var params = {
Name: name,
Id: id
};
$.ajax({
cache:false,
url: '#Url.Action("EditName", "Order")',
data: JSON.stringify(params),
type: "POST",
success: function (data) {
window.location.href=data.Url;//doesnt work passes null model
}
});
}
[HttpPost]
public ActionResult EditName(string name,int id)
{
var product= GetProduct(id);
product.Name=name;
UpdateProduct(product);
var model=new ProdModel(){id=id};
return Json(new
{
Url = Url.Action("Test","Order",new{model=product})
},JsonRequestBehavior.AllowGet);
}
Try as follows
In Edit Action try returning the model instead of url,
public josnResult EditName(string name,int id)
{
var product= GetProduct(id);
product.Name=name;
UpdateProduct(product);
var model=new ProdModel(){id=id};
return Json(model,JsonRequestBehavior.AllowGet);
}
Then in ajax Success call you can make another call to Test Action
$.ajax({
cache:false,
url: '#Url.Action("EditName", "Order")',
data: JSON.stringify(params),
type: "POST",
success: function (data) {
CallTestAction(data);
}
});
var CallTestAction = function(data) {
$.ajax({
cache:false,
url: '#Url.Action("Test", "Order")',
data: {model = data},
type: "POST",
success: function (data) {
}
});
};

Web Api: PUT/ POST method does not work

Here is my controller;
public class ProductionStateController : ApiController
{
private readonly IFranchiseService _franchiseService;
public ProductionStateController(IFranchiseService franchiseService)
{
_franchiseService = franchiseService;
}
[DataContext]
public string PutProductionState(int id, FranchiseProductionStates state)
{
_franchiseService.ChangeProductionState(id, state);
var redirectToUrl = "List";
return redirectToUrl;
}
}
My ajax call;
self.selectState = function (value) {
$.ajax({
url: "/api/ProductionState",
type: 'PUT',
contentType: 'application/json',
data: "id=3&state=Pending",
success: function (data) {
alert('Load was performed.');
}
});
};
My route;
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
I am getting a 404 File not found error.
Same if I replace the method to be POST.
If I make it GET everyting works.
I am missing something here. Any help will be greatly appreciated.
The web api framework matches action methods which start with the http verb. So PutProductionState is ok as a name.
I was able to make this work. The problems are the following: the second parameter of the action method should be marked with the [FromBody] attribute:
public string PutProductionState(int id, [FromBody] FranchiseProductionStates state)
{
_franchiseService.ChangeProductionState(id, state);
var redirectToUrl = "List";
return redirectToUrl;
}
And the ajax call should look like this:
self.selectState = function (value) {
$.ajax({
url: "/api/ProductionState/3",
type: 'PUT',
contentType: 'application/json',
data: "'Pending'",
success: function (data) {
alert('Load was performed.');
}
});
};
Note the id parameter added to the url and the stringified data.
Thanks!
<script>
function CallData(ids) {
debugger;
if (ids != null) {
$.ajax({
url: "EVENT To Call (Which is in Controller)",
data: {
SelId: $("#Control").val()
},
dataType: "json",
type: "POST",
error: function () {
alert("Somehitng went wrong..");
},
success: function (data) {
if (data == "") {
//Do Your tuff
}
}
});
}
}
//In Controller
[HttpPost]
public ActionResult EVENT To Call (Which is in Controller) (int ids)
{
//Do Your Stuff
return Json(Your Object, JsonRequestBehavior.AllowGet);
}

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