I have this model
public class Model
{
public string itemlineId { get; set; }
public string shipmentID { get; set; }
public string containerID { get; set; }
public string containerType { get; set; }
}
I have a dynamic html table, what im trying to do is to post table data through ajax,and send it to the controller
$("body").on("click", "#btnSave", function () {
//Loop through the Table rows and build a JSON array.
var itemlists= new Array();
$("#tblAttachShip TBODY TR").each(function () {
var row = $(this);
var itemList = {};
itemList.itemlineId = row.find("TD").eq(0).html();
itemList.shipmentID = document.getElementById("txtShipmentID").value
itemList.containerID = row.find("TD").eq(1).html();
itemList.containerType = row.find("TD").eq(2).html();
itemlists.push(itemList);
});
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Project/Create",
data: JSON.stringify({ Model : Itemslists}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
so far all okay, when I try to read the post request in the browser I can see that the request has the correct data as json format
Model: [{itemlineId: "aa", shipmentID: "a", containerID: "aa", containerType: "aa"}]}
however when I check the controller the list doesn't contain any elements, and no values has been binded, I checked several posts but I can't figure ouut what I did wrong to bind the json data to the model in the controller
[HttpPost]
public JsonResult Create(List<Model> Model)
{
return Json("Success");
}
EDIT
I think we both jumped the gun a bit there. I did some digging and it looks like the JSON.stringify is actually going to be necessary because of the way that ajax posts the data; I think your issue might actually be with the javascript. When I copied your code, there were errors. I am running this right now which is working. Assuming your posted code was copy and pasted, this:
data: JSON.stringify({ Model : Itemslists}),
should be
data: JSON.stringify({ Model : itemlists}),
Looks like it was just a typo with the name of the array.
Working code:
#{
ViewBag.Title = "Home Page";
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script type="text/javascript">
$("body").on("click", "#btnSave", function () {
//Loop through the Table rows and build a JSON array.
var itemlists = new Array();
$("#tblAttachShip TBODY TR").each(function () {
var row = $(this);
var itemList = {};
itemList.itemlineId = row.find("TD").eq(0).html();
itemList.shipmentID = document.getElementById("txtShipmentID").value
itemList.containerID = row.find("TD").eq(1).html();
itemList.containerType = row.find("TD").eq(2).html();
itemlists.push(itemList);
});
//Send the JSON array to Controller using AJAX.
$.ajax({
url: './Home/Create',
type: 'POST',
data: JSON.stringify({ Model: itemlists }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
},
error: function (r) {
alert(JSON.stringify(r));
}
});
});
</script>
<input type="text" id="txtShipmentID" />
<table id="tblAttachShip">
<tbody>
<tr>
<td>aaa</td>
<td>aa</td>
<td>a</td>
</tr>
<tr>
<td>bbb</td>
<td>bb</td>
<td>b</td>
</tr>
</tbody>
</table>
<button id="btnSave">Save</button>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
[HttpPost]
public JsonResult Create(List<Model> Model)
{
return Json(new { Message = "Success" });
}
}
public class Model
{
public string itemlineId { get; set; }
public string shipmentID { get; set; }
public string containerID { get; set; }
public string containerType { get; set; }
}
}
You are stringifying your object:
data: JSON.stringify({ Model : Itemslists}),
So you are passing a string into your controller, when your controller expects a List.
Off the top of my head i'd say try just passing the object e.g.
data: Itemslists,
Or if there is a reason that you need to pass it as a string. Change your controller to receive a string and then deserialize it:
(List<Model>)serializer.Deserialize(jsonString, typeof(List<Model>);
Related
This is my javascript array of json objects
var pObjIds = [{"Id":"2","Name":"small"},{"Id":"3","Name":"average"}]
I have collected my form fields into a FormData() like this
var form = new FormData($(this)[0]);
I have appended the array of json objects to the FormData like this
form.append("Availability", pObjIds);
I have a ViewModel with a property
public List<Item> Availability { get; set; }
The Item class looks like this
public class Item
{
[JsonProperty(PropertyName = "Id")]
public int Id { get; set; }
[JsonProperty(PropertyName = "Name")]
public string Name { get; set; }
}
My controller method to receive the form data is
[HttpPost]
public IActionResult AddSupplier(SupplierVM vm, List<Item> list)
{
if (ModelState.IsValid)
{
}
return View("AddSupplier", vm);
}
My intention is to bind the appended Availability in the formData to the property
public List<Item> Availability { get; set; } in the ViewModel.
The above code is what I have tried but its not binding. Always returning count=0 for Availability.
Are my doing something wrong or is there a better way i can do it?
I have used FormCollection in controller but still not seen the appended array of json objects but i can log it in the console and see that it is appended successfully.
I am using dotnet core 3.0 mvc.
Thanks in advance.
This is the client side code that calls the AddSupplier
var form = new FormData($(this)[0]);
form.append("Availability", pObjIds);
$.ajax({
type: 'POST',
url: '/supplier/addsupplier/',
data: form,
processData: false,
contentType: false,
datatype: 'json',
success: function (result) {
if (result.status == false) {
swal({
title: 'Error!',
text: result.msg,
icon: "error",
button: "Ok",
});
}
},
error: function () {
swal({
title: "Unknown Error!",
text: "unable to process request!",
icon: "error",
button: "Ok",
});
}
});
I have a ViewModel with a property
public List<Item> Availability { get; set; }
My intention is to bind the appended Availability in the formData to the property public List<Item> Availability { get; set; } in the ViewModel.
To achieve your requirement, you can try to append values for FormData object like below.
var form = new FormData($(this)[0]);
//form.append("Availability", pObjIds);
$(pObjIds).each(function (index, el) {
form.append(`Availability[${index}].Id`, el.Id);
form.append(`Availability[${index}].Name`, el.Name);
});
$.ajax({
type: 'POST',
url: '/supplier/addsupplier/',
data: form,
processData: false,
contentType: false,
datatype: 'json',
success: function (result) {
// code logic here
//...
In controller action AddSupplier
[HttpPost]
public IActionResult AddSupplier(SupplierVM vm)
{
//code logic here
View model class SupplierVM
public class SupplierVM
{
public int Id { get; set; }
//other properties
public List<Item> Availability { get; set; }
}
Test Result
I am new to MongoDB. My application is dynamic form builder that lets users add dynamic fields on the form. None of the field on the form is fix or static. The user can add any number and any type of fields such as Textbox, Textarea, Dropdown, Checkbox, Radiobutton etc fields on the form and save the form.
Now want to store the created fields into Database. then saved forms will be used to collect data from the users.
How to pass the Fields from the View to the controller? and to describe a Model and Controller for this (to handle fields)?
I’m using ASP.NET MVC as a frontend MongoDB as a backend
I'm pushing all the fields here:
$('.field').each(function() {
var $this = $(this);
//field type
var fieldType = $this.data('type');
//field label
var fieldLabel = $this.find('.field-label').val();
//field required
var fieldReq = $this.hasClass('required') ? 1 : 0;
//check if this field has choices
if($this.find('.choices li').length >= 1) {
var choices = [];
$this.find('.choices li').each(function() {
var $thisChoice = $(this);
//choice label
var choiceLabel = $thisChoice.find('.choice-label').val();
//choice selected
var choiceSel = $thisChoice.hasClass('selected') ? 1 : 0;
choices.push({
label: choiceLabel,
sel: choiceSel
});
});
}
fields.push({
type: fieldType,
label: fieldLabel,
req: fieldReq,
choices: choices
});
});
Saving Form with Dynamic fields:
var formArray=[];
formArray.push({ name: "formID", value: "formID" }, { name: "formFields", value: "fields" });
var formObject = JSON.stringify(formArray);
$.ajax({
method: "POST",
url:'#Url.Action("Index", "Home")',
data: formObject,
dataType: 'JSON',
success: function (data)
{
console.log(data);
$('.alert').removeClass('hide');
$("html, body").animate({ scrollTop: 0 }, "fast");
//Demo only
$('.alert textarea').val(JSON.stringify(fields));
}
});
Can anyone suggest a Model and Controller for this?
Update
As #stom suggested, I did the following corrections:
Model
namespace Simple_jQuery_Form_Builder.Models
{
public class ControlsAttribute
{
public string id { get; set; }
public string value { get; set; }
public string name { get; set; }
}
public class FormControl:ControlsAttribute
{
public object textBox { get; set; }
public object textArea { get; set; }
public object checkBox { get; set; }
public object radioButton { get; set; }
public object agreeBox { get; set; }
public object selectBox { get; set; }
public object datePicker { get; set; }
}
public class Simple_jQuery_Form_Builder_Model
{
public List<FormControl> controls { get; set; }
public List<FormControl> formEditor { get;set; }
}
}
View
<form method="post" action="~/Controllers/Home/Index">
<div id="sjfb" novalidate>
<div id="form-fields">
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.DisplayFor(model => model.controls);
#Html.DisplayFor(model => model.formEditor);
}
</div>
<button type="submit" class="submit">Save Form</button>
</div>
</form>
Controller
[HttpPost]
public ActionResult Index(Simple_jQuery_Form_Builder_Model model)
{
if (model != null)
return Json("success");
else
return Json("An error has occured");
}
It's supposed to show the saved form in the desired link/div. It shows "success" message. Now I've to show the created form in another view (like the preview)
First create your View Models.
public class FormViewModel
{
public string name { get; set;}
public string value { get; set;}
}
Action methods
This is to load your form in GET request.
public ActionResult Index()
{
return View();
}
This is to post your data in POST request.
[HttpPost]
public ActionResult SaveForm(IEnumerable<FormViewModel> model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
}
Index View
Add this in your Index.cshtml View
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$('#saveInMongo').click(function (e) {
var formArray=[];
formArray.push({ name: "formID", value: "formID" }, { name: "formFields", value: "fields" });
var formObject = JSON.stringify(formArray);
$.ajax({
url: "#Url.Action("Home","SaveForm")",
type: "POST",
data: formObject,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
alert(response);
}
});
});
});
</script>
<input type="button" value="Save In Mongo" id="saveInMongo" />
This should work.
Check this for more.
I am trying to pass my table data from view to controller using java-script but it's not working. I am passing my table data to my model class using java-script.
My model class has array of objects of my shared class in which i'm filling my data.
My shared class is like this:
public class BomItemsDTO : IBomItems
{
public int stockitemid { get; set; }
public string itemname { get; set; }
public int quantity { get; set; }
public string description { get; set; }
public string approvedsupplier { get; set; }
public int priceperunit { get; set; }
public int totalprice { get; set; }
}
My model class is like this:
public class BiddingSecondStepModel
{
public BomItemsDTO[] BomItems { get; set; }
}
My javascript code is this:
<script type="text/javascript">
$("#btnsendtoadvancepurchase").on('click', function () {
var BomItems = [];
$('#tblBom tr').each(function (row, tr) {
BomItems.push({
itemcode: $(tr).find('td:eq(0)').text().trim(),
desc: $(tr).find('td:eq(1)').text(),
quant: $(tr).find('td:eq(2)').text(),
supplier: $(tr).find('td:eq(3)').text(),
});
});
var model = {
BomItems: BomItems
};
debugger;
$.ajax({
url:'#Url.Action("AdvancePurchase", "CreateBid")',
type: "POST",
contentType: 'application/json; charset=utf-8',
data: MODEL,
dataType:'json',
success: function (data) {
alert('Document Saved.');
}
});
});
</script>
My html table is like this which is made dynamically:
<table class="TableID2" id="tblBom">
<thead>
<tr>
<th>Item Code</th>
<th>Description</th>
<th>Quantity</th>
<th>Approved Supplied</th>
<th></th>
</tr>
<tr><td>
TD6915PLBOXSTRG00
</td><td>456 n6</td><td>789456</td><td>aa</td><td><img src="../Content/Images/deleterow.png" class="btnDelete"></td></tr><tr><td>
SG0242108JAD1HG10
</td><td>125 v4</td><td>456123</td><td>aa</td><td><img src="../Content/Images/deleterow.png" class="btnDelete"></td></tr></thead>
</table>
My controller action is this:
[HttpPost]
public ActionResult AdvancePurchase(BiddingSecondStepModel data)
{
}
I haven't written code for what i have to do with my data when controller action receives the data.
My main concern is how to send data of my table from view to my controller action.
Please help.
Thanks in advance
maybe your model in js didn't create right!
you can get your model with serialize form instead of get each fields like that.for do this first define id for your form and in script get your whole form by id, then you can serialize all fields of model that is in your form like:
var model=$("#Myform").serialize();
now you can bind your model after your url and send it to your controller like:
$.ajax({
url:'#Url.Action("AdvancePurchase","CreateBid")?'+model,
type: "POST",
success: function (data) {
alert('Document Saved.');
}
});
it will work.
My controller Action:
[HttpPost]
public ActionResult H80Count(IEnumerable<H80SearchCriteria> model)
{
do some stuff and return Json;
}
My model:
public class H80SearchCriteria
{
public int ID { get; set; }
public int Operator { get; set; }
public string FieldID { get; set; }
public string Kriterie { get; set; }
}
My Javascript:
var SearchCriteria = [];
var i = 0;
$('#tableSearchValues > tbody').find('tr').each(function () {
i += 1;
var row = {
ID : i,
Operator : $(this).data('operator'),
FieldID : $(this).data('fieldid'),
Kriterie: $(this).data('kriterie')
};
SearchCriteria.push(row);
});
var url = '/MyController/H80Count';
var data = JSON.stringify(SearchCriteria) ;
$.ajax({
type: 'POST',
url: url,
data: data,
etc...
The Json that is passed looks like this:
[{"ID":1,"Operator":1,"FieldID":1,"Kriterie":11211},{"ID":2,"Operator":1,"FieldID":1,"Kriterie":11211}]
I can't see why it is not parsed correctly. What am I missing?
I think you forgot the contentType: 'application/json' on ajax function.
It works for me.
try this instead of IEnumerable use array and place [FromUri] or [FromBody] which looks for values in the Uri or Body of the request.
[HttpPost]
public ActionResult H80Count([FromUri] H80SearchCriteria[] model)
{
do some stuff and return Json;
}
and dont forget to set the traditional ajax settings as true
$.ajax({
type: 'POST',
url: url,
data: data,
traditional: true
});
I have an AJAX-enabled WCF service with the following signature:
[OperationContract]
[WebGet]
public JQGridContract GetJQGrid(int entityIndex)
And the following data contract:
[DataContract]
public class JQGridContract
{
[DataContract]
public class Row
{
[DataMember]
public int id { get; set; }
[DataMember]
public List<string> cell { get; set; }
public Row()
{
cell = new List<string>();
}
}
[DataMember]
public int page { get; set; }
[DataMember]
public int total { get; set; }
[DataMember]
public int records { get; set; }
[DataMember]
public List<Row> rows { get; set; }
public JQGridContract()
{
rows = new List<Row>();
}
}
Basically I need to change the postData of the client-side jqGrid to send 'entityIndex' to this service.
I've read how its supposed to function and from what I can tell this should work:
function loadGrid() {
$("#jqGrid").jqGrid({
postData: { entityIndex : function () { // modify the data posted to AJAX call here
return 6;
})
},
gridComplete: function () {
$("#jqGrid").setGridParam({ datatype: 'local' });
},
datatype: function (pdata) {
getData(pdata);
},
And here is the getData() function:
function getData(pdata) {
var params = new Object();
alert(pdata.entityIndex()); // this displays '6', correctly
params.entityIndex = pdata.entityIndex();
$.ajax(
{
type: "GET",
contentType: "application/json; charset=utf-8",
url: "AJAXService.svc/GetJQGrid",
data: JSON.stringify(params),
dataType: "json",
success: function (data, textStatus) {
if (textStatus == "success") {
var thegrid = $("#jqGrid")[0];
thegrid.addJSONData(data.d);
}
},
error: function (data, textStatus) {
alert('An error has occured retrieving data!');
}
});
Ive confirmed the following in Firebug:
1) The json params are correct : {"entityIndex":6}
2) The AJAX service returns JSON data to the grid, its just the wrong data
And here is the wierd part:
I logged the 'entityIndex' thats actually working inside the WCF operation -- and its ALWAYS coming up as 0?
Thanks.
I will not criticize the style of your program. I could write too many things about this. :-)
You current main problem could be solved with the usage JSON.stringify(pdata.entityIndex()) instead of JSON.stringify(params) or with the usage of another BodyStyle of the WFC method (see here for details)
I got it working, it is close to what Oleg said, just that you do not need to do JSON.stringify.
If you have WebMessageBodyStyle.WrappedRequest, this works:
data: { entityIndex: pdata.entityIndex() },
OR if you have no BodyStyle, this works:
data: { "entityIndex": pdata.entityIndex() },