How to fetch model values (IList<Model>) in the script and pass the data to the controller?
I want to pass the data like :
array 0 : id : 1,id:2
array1 : id : 3,id:4
Suppose you have a model with column names(as in Database)
EmployeeId, ProjectId,WorklogDate, OnlineHours, OfflineHours
So you would need to create two arrays in jQuery code, one would be main array with all model values(Model List), while second would be array in which you would have value for each Model
So considering above given columns names, your jquery code would be
//call this on button click or on any event, to loop on all model list
//with class .WorkData
var workslogs = [];
$(".WorkData").each(function () {
//Get Values for each Model in an array and push it in Main array
worklog = {
EmployeeId: $('#EmployeeId').val(),
ProjectId: $('#select1').val(),
WorklogDate: $("#Worklogdate").val(),
OnlineHours: $('.onlinetxt').val(),
OfflineHours: $('.oflinetxt').val(),
}
}
worklogs.push(worklog);
//post ajax request to controller, after getting all values in array
//pass data in JSON.stringify to make it as string
$.post('/URL', { Checkedstr: JSON.stringify(worklogs) }, function (data) {
//success code here
});
})
After pushing data in an array, pass data to the controller using ajax to the controller as a string and then get data as a string controller, in the controller you need to deserialize data and loop through each model data.
C# code would be
[HttpPost]
public JsonResult MethodName(string Checkedstr)
{
//WorkLog is model name
WorkLog wl = new WorkLog();
//Deserialize string into Model list item here
List<WorkLog> Worklogitems = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<List<WorkLog>>(Checkedstr);
foreach(var item in Worklogitems)
{
//do soemthing with each model item
}
return Json(true);
}
In the above code, we are Deserializing string into model list and looping through each model item.
Note: passing sensitive data in method like this is not good considering security
If you are using .NET Core, then things might differ a little bit, suppose this is your code on Front-end
var ListToPass= [
{ id: 1, name: 'John' },
{ id: 2, name: 'Smith' },
{ id: 3, name: 'Kayla' }
];
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: mycontrolleraction,
data: JSON.stringify(ListToPass)
});
and in the C# controller, you can get values using "FromBody
"
[HttpPost]
public IActionResult NewBranch([FromBody]IEnumerable<ListToPassModel> ListToPass)
{
//do somethinghere
return Ok();
}
That's it, thanks
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly