I try to send antiforgerytoken and yeniTest is filled by some data ( it is not null ) to controller via below code at html page.
var token = document.querySelector('input[name="__RequestVerificationToken"]').value;
$.ajax({
url: '#Url.Action("/TestCevabı")',
type: 'post',
data: { __RequestVerificationToken: token, yeniTest: JSON.stringify(yeniTest)},
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
traditional: true
});
Controller method is like below
[HttpPost]
[ValidateAntiForgeryToken]
public bool TestCevabı(Test yeniTest)
{
///
}
I pass ValidateAntiForgeryToken at controller method.But yeniTest at TestCevabı method is null.
I changed the controller method as below.
[HttpPost]
[ValidateAntiForgeryToken]
public bool TestCevabı(string yeniTest)
{
///
}
and add following code to TestCevabıService
Test çözülenTest = new Test();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(testJsonFormat)))
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(çözülenTest.GetType());
çözülenTest = ser.ReadObject(ms) as Test;
ms.Close();
}
Now antforgerytoken pass and Test object filled
Related
I am new to ASP and I am trying to take a string in my JS code and post it to my controller so that I can use it to query my database.
JavaScript
function findEmployees(userCounty) {
$.ajax({
type: "POST",
dataType: "json",
url: '#Url.Action("Index", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
success: function (response) {
alert(userCounty);
},
error: function (response) {
alert("failed");
}
});
}
Controller
[HttpPost]
public ActionResult Index (string userCounty)
{
var query = //use linq to query database
return View(query);
}
I only ever get the "success" alert when I use a JsonResult function in my Controller but I need it to eventually return a LINQ query to the View(); function and that hasn't worked when using a JsonResult function. Any ideas would be helpful. I don't necessarily have to use ajax if there is a better way. I just need a way to pass the string stored in userCounty to my controller.
Please change your controller method like this
[HttpPost]
public ActionResult Index([FromBody]string userCounty)
{
var query = //use linq to query database
return View(query);
}
For viewing the page, you'll need
[HttpGet]
public ActionResult Index()
{
return View();
}
I have been trying to send a list model to controller using ajax but it seems it is not working at all
Model
public string MyModel {
public string myfieldName {get;set;}
}
controller
public JsonResult Create(List<myModel> list)
{
return Json("Success");
}
post request
$("body").on("click", "#btnSave", function () {
var list= new Array();
list = [{ myfieldName: 'ABC' }, { myfieldName: 'DEF' }];
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Project/Create",
data: JSON.stringify({ list }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
so when I send this through, I check the browser and I can see that the request payload is sent with json object list
However when I go to controller the list is not binding it at all, so I check the http.context to check the request payload there and it all empty.
on the other hand when I change the controller like below
sending request with only model
public JsonResult Create(myModel data)
{
return Json("Success");
}
and change the js with below
$("body").on("click", "#btnSave", function () {
var data ={};
data.myfieldName= "test";
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Project/Create",
data: data,
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
the only difference here is that I don't send as json, so my question what is the is the difference between sending model vs a list of model using ajax
and what can I change to get the controller to bind the data or accept a list of model data
noting i'm using .Net core 2.0
Thank you
I usually use this method to send my Model as a List to my Controller method. I will try to show you regarding your scenario, how you can do this:
AJAX:
$("body").on("click", "#btnSave", function () {
var list= new Array();
list = [{ myfieldName: 'ABC'}, { myfieldName: 'DEF'}];
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "#Url.Action("Create","Project")",
data:{"json": JSON.stringify(list)},
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
And you can receive your Model like this in your Create method:
Make sure to import the System.Web.Script.Serialization namespace:
using System.Web.Script.Serialization
[HttpPost]
public JsonResult Create(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
List<string> myfieldName=new List<string>();
//Access your array now
foreach (var item in jsondata)
{
myfieldName.Add(item["myfieldName"]);
}
//Do something with the list here
return Json("Success");
}
Hope this helps you out.
Another method would be to utilize unobtrusive AJAX. All you would need is to install Microsoft jQuery unobtrusive AJAX from your Nuget Package Manager.
Then, in your view, call the following:
#{using (Ajax.BeginForm("Create", "ControllerName", null, new AjaxOptions()
{
HttpMethod = "POST",
// ...
}
}))
{
// Html code goes here
}
And also make sure that you include this at the bottom of your view:
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
Then, you can have a normal ActionResult setup (instead of JsonResult) for your controller and accept an argument of List list.
I was trying to figure out how I get the body of the JSON object, that I was sending with the listed AJAX POST request.
While debugging the UploadJSON method gets called but is having a jsoninput with null content.
//ASP.NET Core
[HttpPost]
public IActionResult UploadJSON([FromBody] IFormCollection jsoninput)
{
var inputBody = jsoninput;
// Writing JSON object content into a file....
return RedirectToAction("Index");
}
//javascript
function uploadJSON(plistArrayForJSON) {
var sendobj = JSON.stringify({ plistArrayForJSON });
$.ajax({
url: 'https://localhost:5001/home/uploadjson',
type: 'POST',
data: sendobj,
contentType: "application/json",
});
}
The JSON you send is not deserializable as IFormCollection.
//ASP.NET Core
[HttpPost]
public IActionResult UploadJSON([FromBody] IList<PlayList> jsoninput)
{
var inputBody = jsoninput;
// Writing JSON object content into a file....
return RedirectToAction("Index");
}
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 am working with mvc4 application. I developed a form using .cshtml file, which inherits the model and has its corresponding controller action.
I am submitting the form using a ajax jquery like,
var body=$('#formId').serialize();
$.ajax({
url: submitAction,
type: "POST",
datatype: "json",
data: body,
success: function (data) {
if (data != null) {
alert("success");
}
});
"body" is fine and it has serialized data and the submitAction is the var which holds my controller action and the controll is transfered there.
EDIT:
My controller looks like,
public JsonResult(ParentModel model) /*here model always hold null values, WHY??*/
{
//stmts..
return Json(new {success=true}, JsonRequestBehaviour.AllowGet);
}
But, there the parameter of my controller action is showing null values. Can someone tell what could be the mistake and how can I resolve it?
$.ajax({
url: submitAction,
type: "POST", <-- you make post, but asp.net mvc controller receives default GET request
data: { model: body},
[HttpPost]
public JsonResult(string model) //<--now you pass string and to Deserialize in ParentModel
{
JavaScriptSerializer jss= new JavaScriptSerializer();
ParentModel pmodel = jss.Deserialize<ParentModel >(model);
return Json(new {success=true}, JsonRequestBehaviour.AllowGet);
}
Try edit data: section in you request,
remove datatype: "json"
And edit type model parameter to string