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

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:

Related

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

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

ASP.NET Core MVC controller receives null for input parameter from ajax call

I have an ajax call:
...
$("#testBtn").click(function (e) {
e.preventDefault();
$.ajax({
url: "/profile/GuestList",
data: {"keytype": "1"},
method: "POST",
contentType: "application/json",
success: function (data) {
...
}
});
});
...
and my controller method:
[HttpPost]
public async Task<IActionResult> GuestList([FromBody]string keytype)
{
try
{
return Ok();
}
catch (Exception ex)
{
}
}
So, inititally I wanted to send an enum type, but that didnt work, so I wanted to send an int with value 1 and I kept getting only 0, then I added [FromBody] and it was the same, at last I switched to string just in case, and now Im getting a null value.
Where I went wrong in all this variations?
Create class
public class KeyTypeViewModel
{
public string Keytype { get; set; }
}
Fix action by removing [FromBody]
[HttpPost]
public async Task<IActionResult> GuestList(KeyTypeViewModel viewModel)
And fix ajax by removing contentType: "application/json" :
$.ajax({
url: "/profile/GuestList",
data: {keytype: "1"},
method: "POST",
success: function (data) {
...
}
You need to create a Dto that has property keytype.
public class SomeDto
{
public string Keytype { get; set; }
}
[HttpPost]
public async Task<IActionResult> GuestList([FromBody]SomeDto dto)
You have to update your data in your Ajax call to a string as you are using string as input parameter in your POST method.
...
$("#testBtn").click(function (e) {
e.preventDefault();
$.ajax({
url: "/profile/GuestList",
data: "1",
method: "POST",
contentType: "application/json",
success: function (data) {
...
}
});
});
...
You must stringify your data.
Try the following:
$.ajax({
url: "/profile/GuestList",
data: JSON.stringify({"keytype": "1"}),
method: "POST",
contentType: "application/json",
success: function (data) {
...
}
});

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)

Javascript function with Ajax calling controller function on MVC .net not working

When I press a button I do this function, i save in one array some parameters from a table row when checked, once done that i call ajax to go to my function called insertarfaltas in my "controllers" folder, the problem is that i can't reach there.
The only output i'm getting is Uncaught
SyntaxError: Invalid flags supplied to RegExp constructor
'insertarfaltas'.
What's wrong? I just want to pass an ARRAY to my controllers function called insertarfaltas.
$('#guardarfaltas').click(function() {
var i = 0;
var alumnes = [];
var fechactual = SaberFechaActual();
$('#tablaalumnos tr').each(function () {
var id = $(this).find("td").eq(0).html();
var checkbox = $(this).find("td").eq(2).html();
var comentario = $(this).find("#comentario").val();
if ($(this).find("input[type=checkbox]").is(":checked")) {
alumnes[i] = [id,comentario,fechactual,hora,codiuf,codicurs,codimodul];
i++;
}
});
alumnes = JSON.stringify(alumnes);
console.log(alumnes);
$.ajax({
url: #Url.Action("insertarfaltas","Faltas"),
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
traditional: true,
data: {alumnes : alumnes},
success: function (data) {
console.log(data);
}
});
---- Controllers folder:
[HttpPost]
[AllowAnonymous]
public String insertarfaltas(String[] alumnes)
{
String[] a = alumnes;
return ("hola ionah");
}
I'm not sure precisely what the problem is because I'm not sure that you have posted the relevant code, but as I said in the comments I have identified that your array isn't of type String[] it is more like array[array[string]] like a multidimensional array or something,
However, I would be tempted to change your binding to an object as this is more descriptive within your code.
Action
public ActionResult AnotherAction(List<MyRequestModel> model)
{
}
Binding Model
public class MyRequestModel
{
public int Id { get; set; }
public string Commentario { get; set; }
public string Fechactual { get; set; }
public string Hora { get; set; }
public string Codiuf { get; set; }
public string Codicurs { get; set; }
public string Codimodul { get; set; }
}
Then change your JavaScript declaration to something along the lines of:
alumnes[i] = {
Id: id,
Comentario: comentario
Fechactual: fechactual,
Hora: hora,
Codiuf: codiuf,
Codicurs: codicurs,
Codimodul: codimodul
};
Try calling JSON.stringify like this:
var sData = JSON.stringify({model: alumnes});
$.ajax({
url: '#Url.Action("insertarfaltas","Faltas")',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
traditional: true,
data: sData,
success: function (data) {
console.log(data);
}
});
I would try converting the two dimensional array to a ViewModel as #Coulton has suggested.
Then use the JSON.stringify method I have suggested.
[HttpPost]
public ActionResult AnotherAction(List<MyRequestModel> model)
{
}
#Coulton is Saying to change your jQuery to Something like this:
$('#guardarfaltas').click(function() {
var i = 0;
var alumnes = [];
var fechactual = SaberFechaActual();
$('#tablaalumnos tr').each(function () {
var id = $(this).find("td").eq(0).html();
var checkbox = $(this).find("td").eq(2).html();
var comentario = $(this).find("#comentario").val();
if ($(this).find("input[type=checkbox]").is(":checked")) {
alumnes[i] = {
Id: id,
Comentario: comentario
Fechactual: fechactual,
Hora: hora,
Codiuf: codiuf,
Codicurs: codicurs,
Codimodul: codimodul
};
i++;
}
});
var sData = JSON.stringify({model: alumnes});
console.log(sData);
$.ajax({
url: '#Url.Action("insertarfaltas","Faltas")',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
traditional: true,
data: sData,
success: function (data) {
console.log(data);
}
});
AND Also create the ViewModel #Coulton suggested: MyRequestModel
EDIT
try taking you URL out the JavaScript:
var url = '#Url.Action("insertarfaltas","Faltas")'
$.ajax({
url: url,
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
traditional: true,
data: sData,
success: function (data) {
console.log(data);
}
});

How to receive data sent using ajax call by Post method in MVC4?

I want to send my ajax data through post method, from my view but I don't how to receive it in the controller method. here is ajax code :
$.ajax({
contentType: 'application/json; charset=utf-8',
method: 'post',
async: false,
url: "Gateway/DB_Rola",
data:Obj,
success: function (Data) {alert("Good");},
error: function () {alert("Error");}
});
Here is controller code :
[HttpPost] // bindig data with class thing
public JsonResult DB_Rola(thing things)
{ ... }
modal class code :
public class thing
{
public int surah { get; set; }
public int ayah { get; set; }
public string verse { get; set; }
}
Now I don't know how to get that object in controller method. I have tried it with get method , there its working fine, problem is with post...
Please try with the below code snippet.
JS
<script>
$(document).ready(function () {
var things = new Object();
things.surah = 1;
things.ayah = 2;
things.verse = "3";
$.ajax({
url: "Home/DB_Rola?count=" + 1,
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
data: JSON.stringify(things),
success: function (result) {
alert('success');
},
error: function (result) {
alert('boo!');
},
});
});
</script>
MODEL
public class thing
{
public int surah { get; set; }
public int ayah { get; set; }
public string verse { get; set; }
}
CONTROLLER
public class HomeController : Controller
{
[HttpPost]
public ActionResult DB_Rola(thing things)
{
return Json(new { IsSuccess = true });
}
}
OUTPUT:
With/Without Count
Update 1 : pass the list[] of objects instead of single object things
<script>
$(document).ready(function () {
var things = new Array();
var test1 = new Object();
test1.surah = 1;
test1.ayah = 2;
test1.verse = "3";
things.push(test1);
var test2 = new Object();
test2.surah = 11;
test2.ayah = 22;
test2.verse = "33";
things.push(test2);
$.ajax({
url: "Home/DB_Rola?count=" + 1,
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
data: JSON.stringify(things),
success: function (result) {
alert('success');
},
error: function (result) {
alert('boo!');
},
});
});
</script>
[HttpPost]
public ActionResult DB_Rola(List<thing> things,int count)
{
return Json(new { IsSuccess = true });
}
Try this It's just an Example,
function SearchProduct () {
var isExcluded = $('#chkisExcluded').is(':checked');
$.ajax({
type: "POST",
url: '#Url.Action("SearchProductManagement","ProductListManagement")',
data: { isExcluded: isExcluded,},
success: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
});
}
Controller
public JsonResult SearchProductManagement(bool isExcluded)
{
//Your code
return Json(data, JsonRequestBehavior.AllowGet);
}
View
<input type="button" value="Go" onclick="return SearchProduct();" class="button next" />
assuming Obj = {surah:somvalue, ayah:somevalue, verse:somevalue}
The problem is the extra parameter count, you don't have a post action that handles count,
so try:
$.ajax({
contentType: 'application/json; charset=utf-8',
method: 'post',
async: false,
url: "Gateway/DB_Rola,
data:Obj,
success: function (Data) {alert("Good");},
error: function () {alert("Error");}
});

Categories