In ASP.NET Core 6 MVC - passing list of object to controller with model object - asp.net-core-mvc

I have a model class like this:
public class DataModel
{
public int CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public List<ViewModel> ViewModel { get; set; }
}
public class ViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
In ASP.NET Core 6.0 MVC, from js file posting data as shown here:
let postedModel = {
CreatedBy :null,
CreatedDate :null,
ViewModel : []
}
postedModel.CreatedBy = "some id";
postedModel.CreatedDate = "today date"
$(".form-fieldset").each(function () {
let formObject = {};
$('form').find('input').each(function (index, element) {
//In cshtml Name attribute given without form index
formObject[$(element).attr('name')] = $(element).val();
})
postedModel.ViewModel.push(formObject)
}
$.ajax({
url: '/ApiController/SaveData',
type: 'POST',
crossDomain: true,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(postedModel),
async: false
})
My api controller looks like this:
public async Task<IActionResult> SaveData([FromBody] DataModel postedModel)
{
}
but I am getting null in the api controller.
What am I doing wrong? Please help.

Related

Unable to pass data from jQuery.ajax to .net Core 2.1 Actionresult

I want to send data to a .net core 2.1 Action method. I collect the data with jQuery and send it with Ajax. When inspecting the payload the object I want to send is there. But the method wont recivie it. All the values are Null.
The Code:
C#
public class Customer
{
public int CustomerID { get; set; }
public string Name { get; set; }
public string OrgNumber { get; set; }
public string AdressLine1 { get; set; }
public string AdressLine2 { get; set; }
public string ZipCode { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Image { get; set; }
public int? StatusID { get; set; }
}
[HttpPost]
public async Task<IActionResult> Edit(Customer customer)
{
}
return View();
JavaScript
var customerObject = {
CustomerID: customerID,
Name: customerName,
OrgNumber: orgNumber,
AdressLine1: adressOne,
AdressLine2: adressTwo,
ZipCode: zipCode,
City: City,
Country: Country,
Image: customerImage,
StatusID: statusId
}
var url = `#Url.Action("Edit")`;
var postData = $.ajax({
url: url,
dataType: "json",
contentType: "application/json;",
data: { data: JSON.stringify(customerObject) },
method: 'POST',
async: true,
crossDomain: true
});
Payload from browser
data=%7B%22CustomerID%22%3A%2211%22%2C%22Name%22%3A%22Bambino+Kran%22%2C%22OrgNumber%22%3A%22456456131%22%2C%22AdressLine1%22%3A%22Lustikullagatan66%22%2C%22AdressLine2%22%3A%22%22%2C%22ZipCode%22%3A%2216578%22%2C%22City%22%3A%22H%C3%A4sselby%22%2C%22Country%22%3A%22%C3%96zbeckistan%22%2C%22Image%22%3A%22%22%2C%22StatusID%22%3A%221%22%7D
Payload deserialized:
{"CustomerID":"11","Name":"Bambino Kran","OrgNumber":"456456131","AdressLine1":"Lustikullagatan66","AdressLine2":"","ZipCode":"16578","City":"Hässelby","Country":"Özbeckistan","Image":"","StatusID":"1"}
Found this with a little bit of searching and solved it:
jObject

Posting a complex object through ajax along with other simple types

I know that this question has been asked like a hundred times, but I can't figure it out.
I have an ajax call like
function saveBox()
{
var postModel = createBoxPostModel();
showLoader();
$.ajax({
async: true,
type: 'post',
url: '#(Url.BuildAction<IncomingGoodsVerificationController>(x => x.SaveWorkUnitForBox(null, null, null)))',
data: { jsonPostModel: postModel, boxItemKey: boxItemKey, itemKey: itemKey },
success: function (data, status) {
...
},
error: function (jqXHR, textStatus, errorThrown) {
hideLoader();
displayErrorMessagePopup('Error in saving box! ', errorThrown, 'error-msgs');
}
});
}
and the controller method is like
[HttpPost]
public JsonResult SaveWorkUnitForBox(NewWorkUnitBoxModel postModel, string boxItemKey, string itemKey)
{
....
}
The NewWorkUnitBoxModel is
public class NewWorkUnitBoxModel
{
public NewWorkUnitBoxModel();
public string AlternativeWorkUnitNumer { get; set; }
public string Barcode { get; set; }
public int ChooseType { get; set; }
public decimal? GrossWeight { get; set; }
public long IdCompany { get; set; }
public long? IdPackagingType { get; set; }
public long? IdWorkUnitSubType { get; set; }
public decimal? NetWeight { get; set; }
public string Tone { get; set; }
public decimal? Volume { get; set; }
public long? WorkUnitNumber2 { get; set; }
}
and yet when the controller action is called is either null or the object has no value for each of its properties.
I tried several ways:
data: { jsonPostModel: postModel, boxItemKey: boxItemKey, itemKey: itemKey }
data: { jsonPostModel: JSON.stringify(postModel), boxItemKey: boxItemKey, itemKey: itemKey }
Putting all action parameters inside a request class
None of these worked. Client-side the model is loaded correctly, and by using ModelBinders I also looked inside the HtmlRequest and data had arrived on the server. I only solved with changing the type to a string and deserialize it inside the action.
How can I make it automatically deserialize the model?

How to pass IEnumerable model to controller

My model is
public class InvBrojeviModel
{
public int rb { get; set; }
public int id_ulaz_sredstava { get; set; }
public int? inv_broj { get; set; }
public string serijski_broj { get; set; }
public int id_sifra { get; set; }
}
I'm trying to pass this model to controller with an ajax call
var m = '#Html.Raw(Json.Encode(Model))';
$.ajax({
url: "/Ulazna_Dokumenta/InvBrojevi_Post",
type: 'POST',
data: JSON.stringify(m),
dataType: 'json',
success: function (data) {
alert("OK");
}
});
I can see the model is serialized. Serialized structure is
"[{\"rb\":6477,\"id_ulaz_sredstava\":308,\"inv_broj\":6477,\"serijski_broj\":null,\"id_sifra\":29},{\"rb\":6478,\"id_ulaz_sredstava\":308,\"inv_broj\":6478,\"serijski_broj\":null,\"id_sifra\":29},{\"rb\":6479,\"id_ulaz_sredstava\":308,\"inv_broj\":6479,\"serijski_broj\":null,\"id_sifra\":29},{\"rb\":6480,\"id_ulaz_sredstava\":308,\"inv_broj\":6480,\"serijski_broj\":null,\"id_sifra\":29}]":
But in controller the input parameter is NULL. The controller is
[HttpPost]
public ActionResult InvBrojevi_Post(IEnumerable<Magacin.Models.InvBrojeviModel> _invBrojeviModel)
{
return Json("test");
}
The input parameter _invBrojeviModel is NULL. Why?

Ajax post model to controller action

In mvc4 i am trying to Post model data from view to controller using Jquery Ajax but don't now what's wrong with this code can any one help me in this matter.
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#save").click(function () {
$("#content").html("<b>Please Wait...</b>");
var dataObject = {
empid: 1,
EmployeeName: "rizwan",
Address: "lahore",
Country: "pakistan",
Salary: "35000.00",
DepartmentName: "Field"
}
$.ajax({
type: "POST",
url: "/Home/Index",
data: dataObject,
success: function (data)
{
$("#empname").val(''),
$("#empadd").val(''),
$("#empcountry").val(''),
$("#empsalary").val(''),
$("#empdeptname").val(''),
$("#content").html("<div class='success'>"+data+"</div>")
},
error: function (ehr)
{
$("#content").html("<div class='failed'>Error! Please try again</div>");
},
})
});
});
</script>
This is my controller action code who just receive the value of object and save into database
Problem is that i failed to receive values at controller action side.
Please help me.....
[HttpPost]
public ActionResult Index(userview dataObject)
{
department dept = new department();
employee emp = new employee();
string message = "";
try
{
emp.employeeName = dataObject.EmployeeName;
emp.address = dataObject.Address;
emp.country = dataObject.Country;
emp.salary = dataObject.Salary;
dept.departmentName = dataObject.DepartmentName;
db.employees.Add(emp);
db.departments.Add(dept);
db.SaveChanges();
}
catch(Exception ex)
{
message = "Error! Please try again";
}
if (Request.IsAjaxRequest())
{
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
ViewBag.message = message;
return View();
}
This is my model class
public class userview
{
public int empId { get; set; }
public string EmployeeName { get; set; }
public string Address { get; set; }
public string Country { get; set; }
public decimal Salary { get; set; }
public string DepartmentName { get; set; }
}
Try using JSON.stringify
$.ajax({
type: "POST",
url: "/Home/Index",
data: JSON.stringify(dataObject), //Here is the change
success: function (data)
{
$("#empname").val(''),
$("#empadd").val(''),
$("#empcountry").val(''),
$("#empsalary").val(''),
$("#empdeptname").val(''),
$("#content").html("<div class='success'>"+data+"</div>")
},
error: function (ehr)
{
$("#content").html("<div class='failed'>Error! Please try again</div>");
},
})
You can implement BindModel yourself! get the json string and deserialize to your entity.
public class JsonBinder<T> : System.Web.Mvc.IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
using (var reader = new System.IO.StreamReader(controllerContext.HttpContext.Request.InputStream))
{
//set stream position 0, maybe previous action already read the stream.
controllerContext.HttpContext.Request.InputStream.Position = 0;
string json = reader.ReadToEnd();
if (string.IsNullOrEmpty(json) == false)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
object jsonData = serializer.DeserializeObject(json);
return serializer.Deserialize<T>(json);
}
else
{
return null;
}
}
}
}
and set the JsonBinder to the post method like
[HttpPost]
public ActionResult Index([ModelBinder(typeof(JsonBinder<userview>))] userview dataObject)
{
}
the other solution
I found that you could set DataContract to the class of Model, and set DataMember to the Properties of the class.
edit the class like this
[DataContract]
public class userview
{
[DataMember]
public int empId { get; set; }
[DataMember]
public string EmployeeName { get; set; }
[DataMember]
public string Address { get; set; }
[DataMember]
public string Country { get; set; }
[DataMember]
public decimal Salary { get; set; }
[DataMember]
public string DepartmentName { get; set; }
}
and you should add library reference "System.Runtime.Serialization"
Hope it works for you.

AJAX post to asp.net MVC controller method not working

I have this method in my controller:
[HttpPost]
public ActionResult Create(StatusMessage statusMessage, int foreignKey, int statusMessageType)
{
//Do something
}
This is how my StatusMessage model looks like:
public abstract class StatusMessage
{
[Key]
public int Id { get; set; }
/// <summary>
/// Message
/// </summary>
/// [Required]
public string Description { get; set; }
public DateTime CreationDate { get; set; }
public int UseraccountId { get; set; }
public virtual Useraccount Useraccount { get; set; }
}
And I'd like to send a post via jquery ajax to my controller:
function sendForm(message, foreignKey, statusMessageType, target) {
var statusMessage = {
Description: "This is a test message"
};
$.ajax({
url: target,
type: "POST",
contentType: 'application/json',
data: JSON.stringify({
statusMessage: statusMessage,
foreignKey: foreignKey,
statusMessageType: statusMessageType
}),
success: ajaxOnSuccess,
error: function (jqXHR, exception) {
alert(exception);
}
});
}
But the POST isn't sent correctly.
Through testing I figured already out that the problem is the StatusMessage class. If I replace it by a string, everything is working fine.
Why you have defined your class as abstract, controller won't be able to create its instance
Define you class as
public class StatusMessage
for info http://www.codeproject.com/Articles/6118/All-about-abstract-classes
Your ajax post is not working because StatusMessage is an abstract class and you (or the controller) cannot create an instance of it. You should either make it a concrete class or derive another class from it.

Resources