>
I .net core 2.2 This is the object Object:
[Serializable]
public class oob
{
public int i { get; set; }
public string j { get; set; }
}
this is the action in "Home" Controller named Gett that takes oob as input from ajax
[HttpGet]
public IActionResult Gett(oob ww)
{
return Ok(ww);
}
Ajax
{
$.ajax({
type: "Get",
url: "Home/gett",
data: { ww: JSON.stringify({i:55,j:"weqe"})},
dataType: "json",
contentType:"json",
success: function (f) {
console.log(f);
},
error: function (f) {
console.log(f);
}
});
});
When request is made ,at the Gett(oob ww) i get an object with value of i=0 and j=null
Ideally you should not pass object to a GET request, for posting object, you should use POST.
If you still want, you need to change your GET method like following using FromQuery.
[HttpGet]
public IActionResult Gett([FromQuery] oob ww)
{
return Ok(ww);
}
And change your AJAX call like following.
$.ajax({
type: "Get",
url: "Home/gett",
data: {i:55,j:"weqe"},
dataType: "json",
contentType:"json",
success: function (f) {
console.log(f);
},
error: function (f) {
console.log(f);
}
});
Note: To pass the object you don't need JSON.stringify if you are using FromQuery for your API
Related
I am using .Net Core 2.1. This is the function that takes the value of the input boxName from the user and is supposed to pass it to the controller - Create function when the "save button" is clicked.
<script type="text/javascript">
function Submit() {
var boxName = $("#boxID").val();
alert(boxName);
UNTIL HERE EVERYTHING IS FINE - THE ALERT RETURNS THE CORRECT VALUE
$.ajax({
type: "POST",
contentType: "application/json",
url: '/Box/Create',
datatype: 'json',
data: JSON.stringify({ ID: "#Model.Id", BoxName: boxName }),
success: function (response) {
alert("Box created");
}
error: function (response) {
alert("error");
}
});
}
IN THE CONTROLLER
public ActionResult Create(int ID, string BoxName)
{
Box _Box = new Box();
_Box.Name= BoxName;
_db.Boxes.Add(_Box);
_db.SaveChanges();
return RedirectToAction("Index");
}
THE STRING BoxName RECEIVED AS A PARAMETER FROM THE AJAX IS NULL
I even tried
public ActionResult Create([Bind(Include = "ID,BoxName")] Box Box)
but it didn't work either. The error was
Include is not a valid named attribute argument
Any help is appreciated.
Remove the content Type and don't use stringify. So your ajax call becomes
$.ajax({
type: "POST",
url: '/Box/Create',
datatype: 'json',
data: { ID: "#Model.Id", BoxName: boxName },
success: function (response) {
alert("Box created");
}
Edit: This is partially wrong though you should do it for clarity. If there is only one action and the verb is not specified in your controller, the action is done anyway regardless if it's POST or GET.
You are using a POST verb in your ajax, by default all actions in the controller are GET. Add the [HttpPost] attribute above your controller action.
[HttpPost]
public ActionResult Create(int ID, string BoxName)
{
...
}
You should create a binding from the body of the request : ie:
class CreateBinding {
public string ID { get; set;}
public string BoxName { get; set; }
}
And in you controller:
[HttpPost]
Public ActionResult Create([FromBody] CreateBinding binding)
{
var id = binding.ID;
var name = binding.BoxName;
....
}
I'm new to .net core MVC and am trying to execute an Ajax post similar to .net framework MVC. I'm simply trying to POST a single int value to the controller action below. The Ajax call hits the controller, but the action parameter is always 0. I verified that the correct integer value is being sent in the Ajax request payload. What am I missing?
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Ajax_GenerateSecretNum([FromBody]int lower)
{
return Json(new { success = true });
}
$.ajax({
url: '#Url.Action("Ajax_GenerateSecretNum", "Home")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: { lower: lower },
success: function (response) {
}
});
You could create a model (DTO) for the controller parameter and use JSON.stringify() on your data before posting to the controller.
$.ajax({
url: '#Url.Action("Ajax_GenerateSecretNum", "Home")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({ lower: lower }),
success: function (response) {
}
});
public class ModelDto
{
public int Lower { get; set; }
}
[HttpPost]
public IActionResult Ajax_GenerateSecretNum([FromBody]ModelDto model)
{
// model.Lower should contain your int
return Json(new { success = true });
}
$.ajax({
url: '#Url.Action("Ajax_GenerateSecretNum", "Home")',
type: 'POST',
data: { "lower": lower, "upper": upper },
success: function (response) {
}
});
Changing my jQuery ajax to the above sample solved the issue. I'm not sure why, but it looks like specifying the extra ajax parameters caused the values to fail model binding. After changing the ajax, I was also able to remove the [FromBody] attribute from the controller action.
You can do something like below:
$.ajax({
method: "POST",
data: { "Property1": "value1", "Property2": "value2"},
url: "#Url.Action("Ajax_GenerateSecretNum", "Home")",
success: function (data) {
//success login
},
error: function (data) {
alert('error' + data.status);
}
});
Controller will look like below:
[HttpPost]
public ActionResult Ajax_GenerateSecretNum(ModelClass modelClass)
{
//You logic will be here
}
This is my DisputeController method stub:
[HttpPost]
public virtual ActionResult UpdateDisputeStatus(DisputeUdpateStatusModel model)
{//some code
Here is my Ajax call:
var url = '/dispute/UpdateDisputeStatus';
var disputeStatusObj = {
DisputeId: id,
DisputeStatusId: selectedValue
}
$.ajax({
url: url,
cache: false,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: disputeStatusObj,
success: function (data) {
alert('Status Changed Successfully');
},
error: function (e) {
alert('Error: ' + e.status);
}
});
I know the routing works, as without using the data parameter the code enters my method (obviously without the model in parameters)
I have tried the following data formats:
data: {'DisputeId': DisputeId, 'StatusId': DisputeStatusId},
data: {disputeStatusObj},
data: JSON.Stringify(disputeStatusObj)
using controller methods:
[HttpPost]
public virtual ActionResult UpdateDisputeStatus(string disputeId, string statusId)
[HttpPost]
public virtual ActionResult UpdateDisputeStatus(modelname model)
None of which work. I get Not found errors or 500's.
Bearing in mind that I know the routing is correct, when I send the request with no data, so what am I missing here?
Am I declaring the controller incorrectly?
Verify your model that should be the same name as well as the data type because of while post the value from Jquery that values are not mapping with the property of the model.
#Mike I tried below code
public class DisputeUpdateStatusModel
{
public string DisputeId { get; set; }
public string DisputeStatusId { get; set; }
}
public class DisputeController : Controller
{
[HttpPost]
public virtual ActionResult UpdateDisputeStatus(DisputeUpdateStatusModel model)
{
return new ContentResult() { Content = "OK" };
}
}
script on view as:
<script type="text/javascript">
var disputeStatusObj = {}
disputeStatusObj.model = {
DisputeId: 1,
DisputeStatusId: 1
}
var url = '/dispute/UpdateDisputeStatus';
$.ajax({
url: url,
cache: false,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(disputeStatusObj),
success: function (data) {
alert('Status Changed Successfully');
},
error: function (e) {
alert('Error: ' + e.status);
}
});
</script>
Please see.
If this is not working, can you please show Model class?
thanks for all your input. My solution was a combination of the answers above.
I was unable to get my code to model bind, so I went back to basics.
I took out the contentType: "application/json; charset=utf-8", as suggested by Stephen Muecke, and ditched the model in my controller and replaced it with string disputeId, string statusId and as suggested by Er Pravin Suthar ensured the parametes were called the same thing. Also to note, the data section was sent as data: { disputeId: disputeId, statusId: statusId } with no quotes around the parameter names. So I ended up with:
var statusId = statusDropdown.value;
var disputeId = $("#disputeId").val();
$.ajax({
url: "/Dispute/UpdateDisputeStatus",
data: { disputeId: disputeId, statusId: statusId },
type: 'POST',
success: function (data) {
alert('Success');
},
error: function (e) {
alert('Status not changed' + e.responseText + ' : ' + e.status);
}
});
and the Controller structure is:
[HttpPost]
public virtual ActionResult UpdateDisputeStatus(string disputeId, string statusId)
Thanks Again for all your input!
I need post two argument to method in C#
[HttpPost]
public bool information([FromBody]int idInfromation,[FromBody] string information)
{
.....
return true;
}
with ajax, but my solution doesn´t work. Newtwork tab is showing:
POST http://-----/information/SubmitAnswer 500 (Internal Server Error)
I have this:
var source = { "idInfromation": 5, "information": "Wau" };
$.ajax({
url: "/information/",
type: "POST",
data: source,
dataType: "json",
contentType: "application/json",
success: function (data) {
alert("Complete");
}
});
Thank you for your advice.
You can't pass multiple [FormBody] parameters instead you have to pass parameter as an object.
for example, declare a DTO class
// DTO
public class InformationClass{
public int idInfromation{ get; set; }
public string Information{ get; set; }
}
[HttpPost]
public bool information(InformationDTO Info)
{
.....
return true;
}
to pass object using Json ajax:
// Initialize the object, before adding data to it.
// { } is declarative shorthand for new Object().
var Information= { };
Information.idInfromation= ParseInt($("txtId").val()); // your desired value
Information.Information= $("#Information").val();
// Create a data transfer object (DTO) with the proper structure.
var DTO = { 'Information' : Information};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "InformationService.asmx/information", // or your specified url, if you don't want //use service like url: "/information/",
data: JSON.stringify(DTO),
dataType: "json"
});
Hope this helps,
Thanks.
You can't return two values with [FromBody]. Either create a DTO class or receive it as a JObject.
I am having problems passing a javascript array to an MVC3 controller, not sure what I am doing wrong but this code does work with standard WCF service.
$(function () {
$("button").click(function () {
Poster();
});
});
function Poster() {
var data = [];
data.push(new WidgetProperty("test1", "value1"));
alert(data.length);
$.post("Home/Test", {test : data});
}
function WidgetProperty(name, value) {
this.Name = name;
this.Value = value;
}
and controller is
[HttpPost]
public ActionResult Test(WidgetProperty[] test)
{
return View("About");
}
public class WidgetProperty
{
public string Name { get; set; }
public string Value { get; set; }
}
Any ideas why the object that comes to the controller has null values for the properties? Checked with fiddler and it appears it passing the correct values.
Thanks!
You should use JSON.stringify() on your data before you post it, and since you know the data type is JSON, it is best to specify that the data being posted is JSON.
$.post("Home/Test", {test : JSON.stringify(data) }, "json");
Live DEMO
Edit:
I researched this a little more and it seems that you need to include contentType: "application/json" in order for this to work in mvc3:
$.ajax({
type: "POST",
url: "Home/Test",
data: JSON.stringify(data),
success: function(data){},
dataType: "json",
contentType: "application/json"
});