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.
Related
I am making an AJAX POST request to the controller (ASP.NET Core MVC), yet the value for the parameter is coming through as null. I tried several solutions given on StackOverflow. But, I couldn't correct it. Please help.
My view collects class fees information. There may have more than one payment.
$(function () {
$('#sendSlip').click(function (e) {
e.preventDefault();
let fees = new Array(); //To store payment info
let tb = $('#feesTable:eq(0) tbody');
//Collecting info of each payment
tb.find("tr").each(function () {
let row = $(this);
let fee = {};
if (row.find('input:checkbox:first').is(':checked')) {
fee.ClassId = row.find("TD").eq(0).html();
fee.FeeId = row.find("TD").eq(1).html();
fee.Amount = row.find(".fee").html();
fee.Month = row.find(".month").html();
fees.push(fee);
}
});
//Arranging data to send to controller
var data = {
fees: fees,
Bank: $(".bank").val(),
PaidAmount : $(".amount").val(),
PaidDate : $(".date").val()
};
console.log(data);
$.ajax({
type: 'POST',
url: '#Url.Action("StudentPayment_Create", "StudentPayment")',
contentType: "application/json",
headers: { 'RequestVerificationToken': gettoken() },
data: //{ data: JSON.stringify(data) },
JSON.stringify(data) ,
})
});
});
Model
public class StudentPaymentSlipVM
{
public StudentPaymentPaidClassVM fees { get; set; }
public string Bank { get; set; }
public DateTime PaidDate { get; set; }
public int PaidAmount { get; set; }
}
Controller
public ActionResult StudentPayment_Create([FromBody] List<StudentPaymentSlipVM> data)
{
---
}
Object details at runtime
From your attached screenshot for data to be passed to the controller, the data's structure was unmatched with the data model the controller expected.
Assume the data structure for the front-end is correct.
Controller should expect that the received data is a StudentPaymentSlipVM object. While in the StudentPaymentSlipVM object, the fees is a StudentPaymentPaidClassVM array.
Model
public class StudentPaymentSlipVM
{
public List<StudentPaymentPaidClassVM> fees { get; set; }
public string Bank { get; set; }
public DateTime PaidDate { get; set; }
public int PaidAmount { get; set; }
}
Controller
public ActionResult StudentPayment_Create([FromBody] StudentPaymentSlipVM data)
{
}
While from your JQuery part, make sure that your data object to be passed to API must be matched with the data type as your model in the back-end.
var data = {
fees: fees,
Bank: $(".bank").val(),
PaidAmount : parseInt($(".amount").val()),
PaidDate : $(".date").val()
};
I tried to pass my data to controller by binding to a ViewModel (StudentPaymentSlipVM) which has all required definitions. But I couldn't do it. So I changed the way and pass my object to Controller as following way now it is working.
And also I would like to thanks Yong Shun.
Changed the JQuery code
$.ajax({
type: 'POST',
url: '#Url.Action("action", "controller")',
headers: { 'RequestVerificationToken': gettoken() },
data: dataObj,
})
I changed the Controller
[HttpPost]
public ActionResult StudentPayment_Create(List<StudentPaymentPaidClassVM> Fees, string Bank, decimal PaidAmount, DateTime PaidDate)
{
.....
}
I'm trying to update my model whenever a button is clicked. When I log the data I'm sending in the razor file to the console, the data is all there. However, when the controller method is called, the model is empty.
My onclick method:
function addCoupon() {
var code = document.getElementById("coupon-entry").value;
$.ajax({ // Validate coupon first. This is working.
method: "post",
url: `/cart/validate-coupon/` + code,
contentType: "application/json; charset=utf-8"
}).done(result => {
if (result.success) {
var model = #Html.Raw(Json.Serialize(Model));
console.log(model); // Countries and CheckoutData are correct here
$.ajax({
method: "post",
url: `/cart/add-coupon/` + code,
contentType: "application/json; charset=utf-8",
data: model
}).done(result => {
console.log("It worked");
});
}
});
}
My model:
public bool IsPos { get; set; }
public List<CountryDto> Countries { get; set; }
public CheckoutData CheckoutData { get; set; }
public string Payment ProcessorError { get; set; }
public bool DisplayRequiredErrors { get; set; }
public List<string> ValidationErrors { get; set; } = new List<string>();
public PaymentInformationModel PaymentInformation { get; set; } = new PaymentInformationModel();
public bool UseSavedCard { get; set; }
My controller:
[HttpPost("add-coupon/{code}")]
public async Task<IActionResult> AddCouponAsync(string code, CheckoutModel model)
{
// Countries and CheckoutData are null here
}
There were several similar questions posted on here, but they all either had simple models, or had solutions that didn't work for me when I tried them.
Thanks!
You should try changing it to this (otherwise it isn't valid javascript):
(Notice that it needs to be encapsulated in '')
var model = '#Html.Raw(Json.Serialize(Model))';
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>);
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.
MVC 4 Changing multiple display fields based on DropDownListFor selection
I'm trying to follow the above example but I think I'm having problems either with my javascript or my controller.
JavaScript in View
$('#InstitutionDDL').change(function () {
var institutionID = $(this).val();
$.ajax({
type: 'POST',
url: '/Compendia/FillImplementationInfo?InstitutionID=' + institutionID,
dataType: 'json',
contentType: 'application/json',
data: { InstitutionID: institutionID },
success: function (ret) {
$('#RegionImplementedField').val(ret.implementedRegion);
$('#ProvinceImplementedField').val(ret.implementedProvince);
$('#DistrictImplementedField').val(ret.implementedDistrict);
$('#LocationImplementedField').val(ret.implementedLocation);
},
error: function (ex) {
}
});
return false;
});
Controller Action
[HttpGet]
public JsonResult FillImplementationInfo(int InstitutionID)
{
var ret = (from e in db.Institutions
where e.ID == InstitutionID
select new
{
implementedRegion = e.Province.Region.RegionName,
implementedProvince = e.Province.ProvinceName,
implementedDistrict = e.District,
implementedLocation = e.InstitutionAdress
}).FirstOrDefault();
return Json(ret, JsonRequestBehavior.AllowGet);
}
Source of DropDownList in View
<div class="form-group">
#Html.LabelFor(model => model.InstitutionID, "Institution", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.InstitutionID, new SelectList(""), "--Select Institution--", htmlAttributes: new { #class = "form-control", #id ="InstitutionDDL" })
#Html.ValidationMessageFor(model => model.InstitutionID, "", new { #class = "text-danger" })
</div>
</div>
^from which after selecting, I want to pull all related data from connected tables using InstitutionID and put it in their respective textboxes known with IDs ending in #ImplementedField
Debugging Results
After selecting an option from the DropDownList, my script could capture the institutionID up to $.ajax({ data: { InstitutionID: institutionID }. However, it skips the success: function(ret) entirely and goes straight to return false; . Furthermore, the error that is being returned is 500 Internal Server Error, and based on the debugger, ret is being treated everywhere as undefined. I've already tried modifying my controller and/or javascript multiple times but with no success. If I'm having a problem with my linq statement, I'm also posting here my Models. Apologies in advance for the long post, I really have no idea where I went wrong.
Models
public class Compendium
{
public int ID { get; set; }
public int InstitutionID { get; set; }
public string RegionImplemented { get; set; }
public string ProvinceImplemented { get; set; }
public string DistrictImplemented { get; set; }
public string LocationImplemented { get; set; }
public virtual Institution Institution { get; set; }
}
public class Institution
{
public int ID { get; set; }
public int ProvinceID { get; set; }
public District? District { get; set; } //enum
public virtual ICollection<Compendium> Compendia { get; set; }
public virtual Province Province { get; set; }
}
public class Province
{
public int ID { get; set; }
public int RegionID { get; set; }
public virtual Region Region { get; set; }
public string ProvinceName { get; set; }
public virtual ICollection<Institution> Institutions { get; set; }
}
First, this URL pattern with query string is not correct to initiate an AJAX call:
url: '/Compendia/FillImplementationInfo?InstitutionID=' + institutionID,
You need to change int Url.Action or simply remove query string on it:
url: '/Compendia/FillImplementationInfo',
// or
url: '#Url.Action("FillImplementationInfo", "Compendia")'
and then remove contentType: 'application/json' since the return type already declared as JSON with dataType: 'json'.
Second, as a general convention, the HTTP method used by jQuery AJAX call & the controller action method must be match to send the argument data successfully. In view side the AJAX call sent as POST method:
$.ajax({
type: 'POST',
...
});
But the action method uses HTTP GET, which causes AJAX call cannot reach the action method since it only accepts GET request:
[HttpGet]
public JsonResult FillImplementationInfo(int InstitutionID)
{
...
}
Note that you can use either GET or POST method with AJAX call, but ensure both of them are matched each other. Here is an example below:
View (jQuery AJAX)
$.ajax({
type: 'GET', // ensure this HTTP method same as used by controller action method
...
});
Controller
[HttpGet]
public JsonResult FillImplementationInfo(int InstitutionID)
{
...
}