string array values is not passing from JavaScript to controller method [duplicate] - javascript

This question already has answers here:
Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax
(17 answers)
Closed last month.
I am trying to pass the values from JavaScript string array variable into controller method. The method is called but the value is not being passed. Here is my example
Controller
[HttpPost]
public IActionResult ReinstateEmployeeUpdate(List<string> employeeIds)
{
return View( );
}
<script type="text/javascript">
function UpdateEmployee() {
var employeeIds = [];
var employeeIds = ["346", "347"];
$.ajax({
type: "POST",
contentType: "application/json",
headers: { 'Content-Type': 'application/json' },
url: "/Employee/ReinstateEmployeeUpdate",
dataType: "json",
data: JSON.stringify(employeeIds),
success: function (response) {
console.log(response);
},
error: function (response) {
console.log(response.responseText);
}
});
}
</script>

You could try as below:
[HttpPost]
public IActionResult ReinstateEmployeeUpdate([FromBody]List<string> employeeIds)
{
return View( );
}

Related

how can I pass html model to controller from javascript [duplicate]

This question already has answers here:
Send JSON data via POST (ajax) and receive json response from Controller (MVC)
(8 answers)
Closed 2 years ago.
I have the following method in Employee controller UpdateEmployee. I want to pass updated value of employee model from html to controller using javascript function. How can I pass model from javascript to Controller, please help
[HttpPost]
public IActionResult UpdateEmployee(Employee emp)
{
}
I want to pass the model from JavaScript to controller
var url = "/Employee/UpdateEmployee?
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If you want to get json data in action,you need to use [FromBody],here is a demo worked:
Controller:
public class EmployeeController:Controller
{
[HttpPost]
public IActionResult UpdateEmployee([FromBody]Employee emp)
{
return Json(emp);
}
}
Model:
public class Employee
{
public int id { get; set; }
public string name { get; set; }
}
ajax:
<script>
var url = "/Employee/UpdateEmployee"
var datas = {
id: 1,
name: 'nm'
}
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(datas),
success: function (data) {
console.log(data)
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
})
</script>
result:

How do I pass a JSON object from ajax to ASP.net page

I have the following code that sends JSON objects to a MVC controller through POST, I have no idea why its not working, any suggestions?
JS
function Update()
{
var objects = $(".Classes");
items = [];
objects.each(function () {
items .push({
"Id": $(this).find(".input").attr('id'),
"Value": $(this).find(".input2").val()
});
});
$.ajax({
type: "POST",
url: "/A/Update",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify(items),
contentType: "application/json",
dataType: "json",
success: function (response) {
}
});
}
Model
public class Update{
public string Id{get;set;}
public string Value{ get; set; }
}
Task
[HttpPost("Update")]
public async Task<JsonResult> Update(IList <Update> items)
{...}
The task runs but JSON objects never deserialize to the model, I always get items of count 0.
you must be change your code data:{"items":JSON.stringify(items)} because you must be send Post data name
then change code to this code
function Update()
{
var objects = $(".Classes");
items = [];
objects.each(function () {
items .push({
"Id": $(this).find(".input").attr('id'),
"Value": $(this).find(".input2").val()
});
});
$.ajax({
type: "POST",
url: "/A/Update",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data:{"items":JSON.stringify(items)},
contentType: "application/json",
dataType: "json",
success: function (response) {
}
});
}
The only change is to use [FromBody] to let model binding system read post data from request body and bind to your object :
public async Task<JsonResult> Update([FromBody]IList<Update> items)

ajax call to Controller Action with an Object as parameter

I have an ajax call to a Controller on an ASP.NET MVC solution that looks like this:
$.ajax({
url: "ControllerClass/ControllerMethod?date=" + date,
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (result) {
globalVariable = result; // This is for later...
DoSomething(result);
},
async: true,
processData: false
})
The controller once it has done all the work on the server side, it returns an Object which contains different property types (an Int, an Array of Int and a List of Objects)
The way that I return that data from the controller back to the JS file is...
return Json(new
{
summary = objectResult
});
The point is that from the JavaScript, now I would like to call a different Controller with the information that I have stored on my globalVariable which is defined in my JavaScript like this:
var globalVariable
That var located at the top of my JS file...
Well, the way I am trying to call back my controller with that variable looks like this:
$.ajax({
url: "ControllerClass/ControllerMethod?result=" + globalVariable,
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (result) {
DoSomethingNewWithThisresult(result)
},
async: true,
processData: false
})
And this is my controller in C#.
public IActionResult ControllerMethod(JsonResult result)
{
DoSomethingHereWithTheResult(result);
}
Why if I put a breakpoing on my last controller, the result variable is empty? I checked on Chrome that the variable contains all the data that I am looking for. Actually, if I just pass one of the properties of the object, it goes to the controller just fine but I can't pass the whole Object...
Try to create your own custom Model instead of using JsonResult as parameter in the action and use it in ajax call this way:
$.ajax({
url: "ControllerClass/ControllerMethod",
type: "POST",
dataType: 'json',
data: { Summary: globalVariable.summary},
contentType: 'application/json; charset=utf-8',
success: function (result) {
DoSomethingNewWithThisresult(result)
}
})
public class YourClass
{
public string Summary { get; set;}//// string type or whatever it is
}
public IActionResult ControllerMethod(YourClass result)
{
DoSomethingHereWithTheResult(result);
}
alternatively you can also use JSON.stringify to serialize your object this way:
var customObject={
"Summary" : globalVariable.summary
};
$.ajax({
url: "ControllerClass/ControllerMethod",
type: "POST",
dataType: 'json',
data: JSON.stringify(customObject),
contentType: 'application/json; charset=utf-8',
success: function (result) {
DoSomethingNewWithThisresult(result)
}
})
Assuming this is a Web API controller, there are multiple ways to read a complex type from the URL - (there are also similar options to MVC controllers)
If the parameters are passed in the UrL, and assuming they map 1:1 to your object, you can decorate your object with the [FromUri] attribute, example:
public class GeoPoint
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
public ValuesController : ApiController
{
public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }
}
Another option which gives you more flexibility controlling the creation of your object and populating the parameters is by using the IModelBinder interface and [ModelBinder] attribute.
You can implement the IModelBinder interface with the only method "BindModel" to access the HTTP request just right before your Controller method is called, create your object, read the URL query params, set the values in your object then finally assign it to the Model property of the bindingContext:
A simple example would be like this:
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType == typeof(MyComplexType))
{
MyComplexType model ;
//You can use the value provider or get it from the HttpRequest
//var theValue = bindingContext.ValueProvider.GetValue ( bindingContext.ModelName);
//var theValue = request.RequestUri.ParseQueryString ( ) ;
if ( new MyComplexTypeConverter( ).TryParse ( actionContext.Request, out model) )
{
bindingContext.Model = model;
return true;
}
else
{
bindingContext.ModelState.AddModelError( bindingContext.ModelName, "Cannot convert request to MyComplexType");
return false;
}
}
return false ;
}
Here is a reference documentation: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Passing values from controller to view

Controller
public ActionResult Booklist(string bookid) {
return View();
}
View
// other codes
url: 'Index/Booklist',
method: 'POST',
success: function (a) {
var windows = window.open('Index/Booklist');
}
But it seem to invoke dispose(); twice..the reason being the first time it calls return View(); and the second var windows = window.open('Admin/GenerateQRCode');
I need to pass data from controller to javascript in sencha and also pass them to the View..is this possible?
Try this:
public ActionResult Booklist([DataSourceRequest] DataSourceRequest request,string bookid)
{
//result should be your data.
var result=0;
return Json(result, JsonRequestBehavior.AllowGet);
}
// other codes
url: 'Index/Booklist',
method: 'POST',
data:{
'bookid': bookid
},
success: function (result) {
}
Please try this.. Sorry earlier one is not working...
$.ajax({
url: "#Url.Action("Booklist", "Home")",
data: {
'bookid': bookid
},
dataType: 'json',
async: true,
type: 'POST',
success: function (response) {
}
});
public ActionResult Booklist( string bookid)
{
var result=1;
return Json(result, JsonRequestBehavior.AllowGet);
}
This is work for me...

How to send HTML content to ASP.NET MVC JSON function?

This is my jQuery code
and the next is my json function to hanlde this jquery code that named InsertMatlabJson.
The problem is no text comes in to the .NET json function. . .
function insert() {
var url = '<%=Url.Content("~/") %>' + "Matlab/InsertMatlabJson";
var text = document.getElementById('MainContent_FreeTextBox1').value
$.ajax({
url: url,
type: 'GET',
data: { text: text},
contentType: 'application/json; charset=utf-8',
success: function (response) {
//your success code
alert("opk");
},
error: function () {
//your error code
alert("no");
}
});
}
and this is my Json function in ASP.NET MVC
public JsonResult InsertMatlabJson(string text)
{
}
This should do it
[AllowHtml]
public JsonResult InsertMatlabJson(string text)
{
}

Categories