I've got main model like this
public class MainModel
{
public Child1 Child1 { get; set; }
public Child2 Child2 { get; set; }
public Child3 Child3 { get; set; }
public Child4 Child4 { get; set; }
}
These all are rendered as follows:
<form id="MainForm">
#Html.Partial("~/Views/Child1.cshtml", Model.Child1)
#Html.Partial("~/Views/Child2.cshtml", Model.Child2)
#Html.Partial("~/Views/Child3.cshtml", Model.Child3)
#Html.Partial("~/Views/Child4.cshtml", Model.Child4)
</form>
I'm trying to post mainform and the action method looks like this
[HttpPost]
public ActionResult Save(MainModel obj)
{
}
Everytime each object (Child1, Child2 etc.) are null. I'm posting form via AJAX as follows:
$.ajax({
url: '#Url.Action("Save","SaveController")',
type: "POST",
data:$("#MainForm").serialize(),
success: function (data) {
}
});
Am i missing something? Is there any other way i can process data? I can not have multiple submits on partial views that's the constraint here.
Any suggestions please.
Related
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.
I'm trying to save a scene created in a browser using Ajax. The data structure is pretty simple. Primary object is Scene and child objects are type of SceneObject.
Here is my Scene model class:
public class Scene
{
[Key]
public int id { get; set; }
[Required]
public string name { get; set; };
public virtual ICollection<SceneItem> sceneItems { get; set; }
}
And this is my SceneItem model class:
public class SceneItem
{
[Key]
public int Id { get; set; }
[Required]
public string name { get; set; }
public float size { get; set;}
public int sceneId { get; set; }
virtual public Scene scene { get; set; }
}
Here is my Ajax code:
var scene ={
sceneItems:[ {
id: 0,
name: "test1",
size: 0.35,
sceneID: 1
},
{
id: 0,
name: "test2",
size: 0.65,
sceneID: 1
}]
}
$.ajax({
type: "POST",
url: "/scene/create",
data: scene
}).done(function (data) {
alert(data);
});
When I execute this Ajax call, in my debug window of the ASP.NET MVC app, I can see all fields are populated except
virtual public Scene scene { get; set; }
from my SceneItem model. And that makes the ModelState.IsValid return false in my controller.
What can I do to make this work in a way that I can post a Scene object along side many SceneItem objects in a single AJAX command and pass ModelState.IsValid and save it into my database using Entity Framework ?
Thank you so much for any help.
add a required field name to your ajax json
var scene ={
id: 0,
name="name",
sceneItems:[
... your data
]
}
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?
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?
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.