I want to receive a formdata as a parameter in actionresult, i don't want to covert into FormData(), and Use Request.Form in action Result, cant i receive data directly, without FormData(), here is what I've tried till now ...
<form ng-show="divPatient" name="PatientForm" ng-submit="AddUpdatePatient()">
<table>
<tr>
<td>
<input class="form-control" type="text" readonly placeholder="Key (Automatic)" ng-model="model.PatientID" />
</td>
<td>
<input name="FirstName" class="form-control" type="text" placeholder="FirstName" ng-model="model.FirstName" ng-minlength="3" required />
</td>
<td>
<input name="LastName" class="form-control" type="text" placeholder="LastName" ng-model="model.LastName" ng-minlength="3" required />
</td>
<td>
<input class="form-control" type="text" placeholder="Disease" ng-model="Disease" name="model.Disease" ng-minlength="3" required />
</td>
<td>
<input class="form-control" type="number" placeholder="Phone No." ng-model="model.PhoneNo" name="PhoneNo" ng-pattern="/^[789]\d{9}$/" required />
</td>
<td>
<input type="file" onchange="angular.element(this).scope().selectFileforUpload(this.files)" ng-model="model.PhotoURL" value="" class="form-control profilePic" required/>
</td>
<td colspan="2" class="saveCancel">
<input type="submit" value="save" class="btn btn-success" ng-disabled="PatientForm.PhoneNo.$dirty && PatientForm.PhoneNo.$invalid || PatientForm.LastName.$dirty && PatientForm.LastName.$invalid || PatientForm.FirstName.$dirty && PatientForm.FirstName.$invalid || PatientForm.Disease.$dirty && PatientForm.Disease.$invalid" />
<input type="button" value="cancel" class="btn btn-primary" ng-click="CancelForm()" />
</td>
</tr>
<tr>
<td></td>
<td><span class="eror-text" ng-show="PatientForm.FirstName.$error.minlength">min 3 letters</span></td>
<td><span class="eror-text" ng-show="PatientForm.LastName.$error.minlength">min 3 letters</span></td>
<td><span class="eror-text" ng-show="PatientForm.Disease.$error.minlength">min 3 letters</span></td>
<td><span class="eror-text" ng-show="PatientForm.PhoneNo.$error.pattern">Invalid phone no</span></td>
</tr>
</table>
</form>
My controller in angularJS
app.controller("StudentCtrl", function ($scope, angularService) {
$scope.model = {};
$scope.AddUpdatePatient = function () {
var getData = angularService.AddPatient($scope.model);
getData.then(function (msg) {
alert(msg.data);
}, function () {
alert('Error in adding record');
});
}
}
My Service in angularJS
app.service("angularService", function ($http) {
// Add Employee
this.AddPatient = function (patientData) {
var response = $http({
withCredentials: true,
headers: { 'Content-Type': undefined },
transformRequest: angular.identity,
method: "post",
url: "AddPatient",
data: patientData,
dataType: "json"
});
return response;
}
}
And my action result
public string AddPatient(Patient patientData) {
//but patientdata fields are all null
}
my MVC Model
using ...
namespace WebApplication3.Models
{
public class Patient
{
public int PatientID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public long PhoneNo { get; set; }
public string Disease { get; set; }
public string PhotoURL { get; set; }
}
}
I wonder why that patientData in action Result is null ??
Try this
$http({ method: 'POST', url: '/ControllerName/AddPatient', data: patientData }).
success(function (data, status, headers, config) {
}).
error(function (data, status, headers, config) {
alert(status);
});
Related
I am trying to send the data from my view to controller, I created a PO, then on the next page I viewed the products to show and to select by the user. but when user select and post the data, controller didn't get that.
Here is a controller data
public IActionResult CreatePO()
{
var LastPO = _context.PurchaseOrders.OrderByDescending(p => p.PONumber).FirstOrDefault();
int TempPO = Convert.ToInt32(LastPO.PONumber.Replace("PO", "")) + 1;
var NewPO = "PO" + TempPO.ToString().PadLeft(6, '0');
ViewBag.NewPO = NewPO;
var UserData = _context.Users.Where(a => a.UserName == User.Identity.Name).SingleOrDefault();
List<Vendor> vendors = _context.Vendors.Where(e => e.CreatedBy == UserData.UserId).ToList();
ViewBag.Vendors = vendors;
return View();
}
[HttpPost]
public IActionResult CreatePO(PurchaseOrder model)
{
if (ModelState.IsValid)
{
var UserData = _context.Users.Where(a => a.UserName == User.Identity.Name).SingleOrDefault();
model.CreatedBy = UserData.UserId;
model.UpdatedBy = UserData.UserId;
return RedirectToAction("AddProduct", new {VendorId = model.VendorId , PONumber = model.PONumber});
}
return RedirectToAction("Index");
}
[HttpGet]
public IActionResult AddProduct(int? VendorId, string? PONumber)
{
if (VendorId == null || PONumber == null)
{
VendorId = 2;
PONumber = "PO00002";
}
List<Product> products = _context.Products.Where(e => e.VendorId == VendorId && e.Stock > 0).ToList();
var VenderData = _context.Vendors.Where(a => a.Id == VendorId).SingleOrDefault();
ViewBag.VendorId = VenderData.VendorName;
ViewBag.PONumber = PONumber;
ViewBag.Products = products;
return View();
}
[HttpPost]
public IActionResult AddProduct(IEnumerable<OrderProducts> ListOfOrderProducts)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
return RedirectToAction("Index");
}
Here is the View of Products to Add
#{
ViewData["Title"] = "Add Products";
}
<link href="~/css/sheet1.css" rel="stylesheet" />
<script src="~/js/pojavascript.js"></script>
<form method="post" onsubmit="return validateForm2()">
<div class="border p-3 mt-4">
<div class="row pb-3">
<h2>
Select Products
</h2>
<hr />
</div>
#if (TempData["SuccessMsg"] != null)
{
<div class="alert alert-dismissible alert-success">
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
<strong>#TempData["SuccessMsg"]</strong>
</div>
}
else if (TempData["ErrorMsg"] != null)
{
<div class="alert alert-dismissible alert-danger">
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
<strong>#TempData["ErrorMsg"]</strong>
</div>
}
<div class="row m-3 mb-3">
<label></label>
<input id="PONumber" readonly value="#ViewBag.PONumber" type="text" class="form-control" />
</div>
<div class="row m-3 mb-3">
<label></label>
<input id="VendorId" readonly value="#ViewBag.VendorId" type="text" class="form-control" />
</div>
<div class="row m-2 mb-3">
<div class="col-md-6 mb-4">
<label>Select Product</label>
<select id="Products" class="form-select">
<option value="0">Select Product</option>
#{
var i = 1;
}
#foreach(var ProData in ViewBag.Products)
{
<option value="tr_#i">(#ProData.SKU) #ProData.ProductName</option>
i = i + 1;
}
</select>
</div>
<div class="col-md-6 mb-4">
<button onclick="AddRow()" type="button" style="margin-top:25px" class="btn btn-primary">
Add
</button>
</div>
</div>
<div class="row m-2 mb-3">
<table class="table table-bordered table-striped" id="POTable">
<thead>
<tr>
<th>
Select
</th>
<th>
Product ID
</th>
<th>
SKU
</th>
<th>
Product Name
</th>
<th style="width:200px">
Add Item
</th>
<th>
Price
</th>
<th>
Total Amount
</th>
</tr>
</thead>
<tbody>
#{i = 1;}
#foreach (var ProData in ViewBag.Products)
{
<tr id="tr_#i">
<input id="PONumber_#i" type="hidden" value="#ViewBag.PONumber">
<input id="VendorId_#i" type="hidden" value="#ViewBag.VendorId">
<input id="CreatedDate_#i" type="hidden" value="#DateTime.Now">
<td>
<input id="Chk_products_#i" class="form-check-input" onclick="CheckRow(this, #i)" type="checkbox">
</td>
<td>
<input id="Pr_ID_#i" type="text" class="form-control" value="#ProData.ProductId">
</td>
<td>
<input id="Pr_Name_#i" type="text" class="form-control" value="#ProData.ProductName">
</td>
<td>
<input id="SKU_#i" type="text" class="form-control" value="#ProData.SKU">
</td>
<td>
<div class="qty">
<button onclick="AddSub(#i ,0)" type="button" class="btn btn-primary" style="margin-bottom:5px">-</button>
<input id="count_#i" type="number" class="form-control" style="width:80px;display:inline-block;" name="qty_#i" value="1">
<button onclick="AddSub(#i ,1)" type="button" class="btn btn-primary" style="margin-bottom:5px">+</button>
</div>
</td>
<td>
<input id="UnitPrice_#i" type="number" class="form-control" value="#ProData.UnitOfPrice">
</td>
<td>
<input id="TAmount_#i" type="number" class="form-control" value="#ProData.UnitOfPrice">
</td>
</tr>
i = i + 1;
}
</tbody>
</table>
<table class="table table-bordered table-striped" style="width:60%;margin-top:30px">
<tr>
<th>Total No of Items</th>
<td>
<input readonly type="text" id="TotItems" class="form-control" value="0" />
</td>
</tr>
<tr>
<th>Total No of Products</th>
<td>
<input readonly type="text" id="TotProducts" class="form-control" value="0" />
</td>
</tr>
<tr>
<th>Total Bill</th>
<td>
<input readonly type="text" id="TotAmount" class="form-control" value="0.00" />
</td>
</tr>
<tr>
<th>Remaining Amount</th>
<td>
<input readonly type="text" id="RemAmount" class="form-control" value="0.00" />
</td>
</tr>
</table>
<div class="row m-2 mb-3">
<div class="mb-2">
<h4 style="display:inline;">Enter amount to pay</h4>
<div class="input-group mb-3" style="width:50%">
<span class="input-group-text">$</span>
<input id="TotPaid" type="text" value="0.00" class="form-control">
<span class="input-group-text">.00</span>
</div>
</div>
</div>
</div>
<button onclick="AjaxFormData()" class="btn btn-primary ms-lg-3" type="button" style="width:100px; margin-top:20px">
Create
</button>
</div>
</form>
Here is the JavaScript Ajax Call Function
function AjaxFormData() {
var ListOfOrderProducts = new Array();
var table = document.getElementById('POTable');
if (table.rows.length != 0) {
for (let i = 1; i < table.rows.length; i++) {
CheckBoxVal = document.getElementById("Chk_products_" + i);
if (CheckBoxVal.checked) {
var memberDetails = {};
memberDetails.VendorId = document.getElementById("VendorId").value;
memberDetails.PONumber = document.getElementById("PONumber").value;
memberDetails.POCreatedDate = "2023-02-13";
memberDetails.ProductId = document.getElementById("Pr_ID_" + i).value;
memberDetails.ProductName = document.getElementById("Pr_Name_" + i).value;
memberDetails.ProductQuantity = document.getElementById("count_" + i).value;
memberDetails.ProductUnitPrice = document.getElementById("UnitPrice_" + i).value;
memberDetails.ProductTotalPrice = document.getElementById("TAmount_" + i).value;
alert(memberDetails.VendorId + " " + memberDetails.PONumber + " " + memberDetails.ProductId);
ListOfOrderProducts.push(memberDetails);
}
}
}
$.ajax({
async: true,
type: "POST",
dataType: "JSON",
contentType: "application/json; charset=utf=8",
url: "AddProduct",
data: JSON.stringify(ListOfOrderProducts),
success: function (data) {
alert("Hello");
},
error: function () {
alert("Error");
}
});
}
I tried to create it by using 3 models
public class OrderProducts
{
[Key]
public int Id { get; set; }
[Required]
public string PONumber { get; set; }
public DateTime POCreatedDate { get; set; }
[Required]
public int ProductId { get; set; }
public string? .....
public class PurchaseOrder
{
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "PO Number")]
public string PONumber { get; set; }
[Required]
public int VendorId{ get; set; }
[Display(Name = "Total Products")]
[ValidateNever]
public int TotalProducts { get; set; }
[Display(Name = "Total Items")]
[ValidateNever]
public int TotalItems { get; set; }
[Display(Name = "Total Amount")]
[ValidateNever]
public double TotalAmount { get; set; }
[Display(Name = "Paid Amount")].....
public class POWithOrders
{
public string PONumber { get; set; }
public string VendorId { get; set; }
public DateTime CreatedDate { get; set; }
public List<OrderProducts> ListOfOrderProducts { get; set; }
}
I need help as my Controller (AddProduct) HTTPPOSt didn't get the Data
I provided all details what I have done and what is happening, My controller is not getting the model data, which I am trying to post from view to controller. I don't know what is going on there.
As you are sending Form Data via AJAX you will also need to add the [FromBody] decoration to the PurchaseOrder parameter.
Example
public IActionResult CreatePO([FromBody]PurchaseOrder model)
Resource
https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-1#sending-form-data-via-ajax
I'm very new to programming and I have a problem with getting roles from a form through FetchAPI.
This is my rest controller
#PostMapping("admin/users/save")
public ResponseEntity<User> save(#RequestBody User user){
return ResponseEntity.ok(userRepo.save(user));
}
This is JS
<script> const url1='http://localhost:8080/api/admin/users/save'
const form=document.getElementById("newUserForm")
form.addEventListener('submit', async (e)=>{
e.preventDefault()
const formData=new FormData(form);
const formDataSerialized = Object.fromEntries(formData)
const jsonobject = {...formDataSerialized}
console.log(formDataSerialized,"formDataSerialized")
try{
const responce= await fetch(url1, {
method: 'POST',
body: JSON.stringify(jsonobject),
headers: {
'Content-Type': 'application/json',
}
});
const json = await responce.json()
console.log(json)
}catch(e){
console.error(e)
alert('there was an error')
}
})
This is how an object should look in DB
[{"id":1,"name":"john","age":23,"country":"USA","email":"john#mail.com","password":"$2a$12$HbAWvSQU/QQ7HuTxdy862.ifBPSev3NdM5Sa1iGUL1YZdopnwbVZm","roles":[{"id":1,"name":"ADMIN","authority":"ADMIN"},
And this is what i get
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.ArrayList<sof.fetchapi314.entity.Role>` from String value (token `JsonToken.VALUE_STRING`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.ArrayList<sof.fetchapi314.entity.Role>` from String value (token `JsonToken.VALUE_STRING`)<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 77] (through reference chain: sof.fetchapi314.entity.User["roles"])]
After sending an object that looks like this
age: "22" country: "22" email: "22" name: "22" password: "22" roles: "2"
Form:
<h1>MyForm</h1>
<form id="newUserForm">
<div class="form-group">
<label class="col-form-label" for="name" style="display: block;
text-align: center;"><b>Name</b></label>
<input class="form-control" type="text" name="name" id="name"
placeholder="Enter name"/>
</div>
<div class="form-group">
<label class="col-form-label" for="age" style="display: block;
text-align: center;"><b>Age</b> </label>
<input class="form-control" type="number" name="age" step="1" min="1" max="150" id="age"
placeholder="Enter age"/>
</div>
<div class="form-group">
<label class="col-form-label" for="country" style="display: block;
text-align: center;"><b>Country</b> </label>
<input class="form-control" type="text" name="country" id="country"
placeholder="Enter country"/>
</div>
<div class="form-group">
<label class="col-form-label" for="email" style="display: block;
text-align: center;"><b>Email</b> </label>
<input class="form-control" type="text" name="email" id="email"
placeholder="Enter email"/>
</div>
<div class="form-group">
<label class="col-form-label" for="password" style="display: block;
text-align: center;"><b>Password</b> </label>
<input class="form-control" type="password" name="password" id="password"
placeholder="Enter password"/>
</div>
<div class="form-group">
<label class="col-form-label" for="roles" style="display: block;
text-align: center;"><b>Roles</b> </label>
<select class="form-select form-control" aria-label="multiple select example" id="roles"
name="roles" size="2" multiple="multiple" >
<option value="1">ADMIN</option>
<option value="2">USER</option>
</select>
</div>
<button type="submit" class="btn btn-success btn-lg">Submit</button>
</form>
I believe the problem is that I send roles as a number, not as an array and I have absolutelu no idea how to fix it. I an BAD in java and pre beginner level in JS.
Edit:
Role Class:
#Entity
#Data
#Table(name="roles")
public class Role implements GrantedAuthority, Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
public Role() {
}
private String name;
#Override
public String toString() {
return this.name;
}
#Override
public String getAuthority() {
return name;
}
}
and User class
#Data
#Entity
#Table(name = "users")
public class User implements UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
private String name;
#Column(name = "age")
private int age;
#Column(name = "country")
private String country;
#Column(name = "email")
String email;
#Column(name = "password")
String password;
#ManyToMany(cascade=CascadeType.MERGE)
#JoinTable(
name="user_role",
joinColumns={#JoinColumn(name="USER_ID", referencedColumnName="id")},
inverseJoinColumns={#JoinColumn(name="ROLE_ID", referencedColumnName="id")})
private List<Role> roles;
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());
}
#Override
public String getUsername() {
return name;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
I have this problem where I try to have an AJAX call to post data the user put in on the webpage to the controller method. The data never arrives at the controller, it always throws an error. The problem is probably that the data the controller expects is not of the same type as what the AJAX call sends to it, but I am really at a loss at what the expected data should look like.
Here's the JS/jQuery that builds the array, which is an array of an array of a table cell's values:
var i = 0;
var cells = new Array(); // cell values in one column
var rows = new Array(); // list of columns (rows)
$('#datatable').find('tr').each(function () {
$('td :not([type="button"],[id="Nr."])', this).each(function () {
cells.push($(this).val());
});
if (i > 0) {
rows.push(cells);
cells = [];
}
i++;
});
this is what the AJAX call looks like:
rows = JSON.stringify({ 'rows': rows });
$.ajax({
url: "/Home/Q_FourthPage",
type: "POST",
datatype: "json",
traditional: true,
data: rows,
success: function (response) {
alert("Success");
console.log("Sucess ", response);
},
error: function (response) {
alert("Error");
console.log("Error ", response);
}
});
The controller is still empty - what parameter should it get in order for the data to arrive as an array of an array of strings/integers/whatever? Thank you.
Edit: This is the view model the Q_FourthPage controller method uses:
public class Q4_Answer_VM
{
public Models.User User { get; set; }
public List<Models.Capacity> Matrix { get; set; } //this is where the data should go
//a capacity describes one row of the table
public Models.QuestionText TMatrix { get; set; }
}
The capacity class looks like this - it is one row of the table.
public class Capacity
{
// This class is a model for the capacity matrix. it represents one column.
//PK
public int ID { get; set; }
//FK
public int Questionnaire_ID { get; set; }
//Values
public String Load { get; set; }
public String Source { get; set; }
public String Goal { get; set; }
public String Frequency { get; set; }
public String Distance { get; set; }
public virtual Questionnaire Questionnaire_ { get; set; }
}
Here's the head of the controller method:
[HttpPost]
public ActionResult Q_FourthPage(ViewModels.Q4_Answer_VM vm)
There are a lot of attributes in these classes - is that why the call fails?
Edit No. 2: The view
Here's the view:
#model MyANTon.ViewModels.Q4_Answer_VM
#{
ViewBag.Title = "myANTon Anforderungserfassung";
ViewBag.HideNavBar = false;
}
#using (Html.BeginForm(Html.BeginForm("Q_FourthPage", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })))
{
<div class="container">
<div align="center">
<ol class="breadcrumb" align="center" text-align="center">
<li class="breadcrumb-item">#Html.ActionLink("Lasten", "Q_Firstpage", "Home", new { #class = "elements" }, null)</li>
<li class="breadcrumb-item">#Html.ActionLink("Lastaufnahme-/abgabe", "Q_Secondpage", "Home", new { #class = "elements" }, null)</li>
<li class="breadcrumb-item">#Html.ActionLink("Weitere Anforderungen", "Q_Thirdpage", "Home", new { #class = "elements" }, null)</li>
<li class="breadcrumb-item"><b><u>#Html.ActionLink("Kapazitäten", "Q_Fourthpage", "Home", new { #class = "elements" }, null)</u></b></li>
<li class="breadcrumb-item">#Html.ActionLink("Auftragserzeugung", "Q_Fifthpage", "Home", new { #class = "elements" }, null)</li>
</ol>
</div>
<div class="jumbotron">
<div>
#Html.TextBox("file", "", new { type = "file" }) <br />
<input type="submit" value="Upload" />
#ViewBag.Message
</div>
<h1>4. Kapazitätsbetrachtung</h1>
<p>Wie viele Fahrzeuge werden benötigt? Um dies auszurechnen wird eine Transportmatrix benötigt.</p>
<p>Ein Beispiel einer Transportmatrix ist in Tabelle 1 zu sehen.</p>
<p>Um die Anzahl der Roboter zu berechnen ist auch eine Angabe der Produktionsschichten relevant:</p>
<ul>
<li>In wie vielen Schichten läuft die Fertigung?</li>
</ul>
<p>
Um mögliche Engpässe oder Umwege zu betrachten ist ein Layout der Produktionsstätte wie in Abbildung 3 von Vorteil.
Idealerweise mit Angaben über andere Verkehrsteilnehmer (Personenverkehr, Staplerverkehr, Kreuzungen).
</p>
<input type="button" id="BtnPlus" name="BtnPlus" class="BtnPlus" value="Zeile hinzufügen (+)" align="center" style="vertical-align: middle" />
<table class="grid" id="datatable" style="table-layout:fixed">
<thead>
<tr style="text-align: center" id="header">
<th style="vertical-align: middle" id="Nr.">Nr.</th>
<th>Last</th>
<th>Quelle</th>
<th>Ziel</th>
<th>Frequenz [/h]</th>
<th>Abstand [m]</th>
<th>Zeile löschen</th>
</thead>
<tbody></tbody>
</table>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" name="Speichern" value="Speichern" id="BtnSave" />
<input type="submit" class="btn btn-default" name="Speichern und weiter" value="Speichern und weiter" />
<input type="button" class="btn btn-default" value="Weiter zu Schritt 5" onclick="#("window.location.href='" + #Url.Action("Q_Fifthpage", "Home") + "'");" />
</div>
</div>
</div>
</div>
}
<script src="~/Scripts/jquery-3.2.1.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.16/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script>
#Scripts.Render("~/bundles/datatables")
Edit no. 3: it works now thanks to the solution provided by user derloopkat below. As a hint: it seems that Ajax and Forms don’t go well together. I had to move the “save” button outside the form (#using...{}).
This worked. The thing is creating an object in json matching the exact names and structure in your model. You don't need to have all members in your json but those who appear should match the model if you want to be able to retrieve their values at server.
var capacities = new Array(); // cell values in one column
$('#datatable').find('tr').each(function () {
var cells = $(this).find('td :not([type="button"],[id="Nr."])');
var capacity = {
Load: cells[0].value,
Source: cells[1].value,
Goal: cells[2].value,
Frequency: cells[3].value,
Distance: cells[4].value
};
capacities.push(capacity);
});
In your Ajax call, dataType is what you expect to get from server, not the type you're sending (that is contentType).
var model = JSON.stringify({ 'Matrix': capacities });
$.ajax({
url: "/Home/Q_FourthPage",
type: "POST",
contentType: "application/json; charset=utf-8",
traditional: true,
data: model,
success: function (response) {
alert("Success");
console.log("Sucess ", response);
},
error: function (response) {
alert("Error");
console.log("Error ", response);
}
});
My table was dummy Html.
<table id="datatable">
<tr>
<td><input type="text" value="11" /></td>
<td><input type="text" value="12" /></td>
<td><input type="text" value="13" /></td>
<td><input type="text" value="14" /></td>
<td><input type="text" value="15" /></td>
</tr>
<tr>
<td><input type="text" value="21" /></td>
<td><input type="text" value="22" /></td>
<td><input type="text" value="23" /></td>
<td><input type="text" value="24" /></td>
<td><input type="text" value="25" /></td>
</tr>
</table>
And action method is:
[HttpPost]
public ActionResult Q_FourthPage(ViewModels.Q4_Answer_VM vm)
{
return View("Index");
}
If you intend to return json from here, then you need to adddataType: 'json' in Ajax call.
I want to read the file name while uploading and rename it,save it to a path. For uploading the file I am using an upload image placed in a table. I am using -
#using (Html.BeginForm("file", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
to read the file name and the row values. But the issue is it reads the value of only first row whereever I click. Here is my code -
HTML -
<div>
#using (Html.BeginForm("file", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr ng-repeat = "{{data in list}}">
<td>{{data.Name}}</td>
<td>{{data.Id}}</td>
<td>
<label for="file">
<i class="fa fa-upload" id="hello" aria-hidden="true" >
</i>
</label>
<input type="file" name="file" id="file" onchange="this.form.submit();" />
<input type="text" name="Name" id="Name" />
<input type="text" name="Id" id="Id" />
</td>
</tr>
</table>
}
</div>
Controller -
public ActionResult file(HttpPostedFileBase file, string Name, string Id)
{
if (file != null && file.ContentLength > 0)
{
string fileName = file.FileName;
string newName = Name;
string fileId = Id;
}
else
{
ViewBag.Message = "You have not specified a file.";
}
return View("UploadPage");
}
Atpresent this is working but when I click on any upload image button, it only takes the first row Name and Id. I am not able to fix it. Please help.
Thanks
you are getting first row because when this.form.submit(); event triggers it will submit the form with all the rows in it and in action its just HttpPostedFileBase not List<HttpPostedFileBase> so it will get the data of first row because it will match the parameter. so one solution is you do
public ActionResult file(List<HttpPostedFileBase> file, List<string> Name, List<string> Id)
{
for (int i = 0; i < file.Count; i++)
{
var name = Name[i];
}
}
and a better way is to use a class
public class UploadFiles
{
public HttpPostedFileBase File { get; set; }
public string Name { get; set; }
public int Id { get; set; }
}
and your view will be
<div>
#using (Html.BeginForm("file", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr ng-repeat = "{{data in list}}">
<td>{{data.Name}}</td>
<td>{{data.Id}}</td>
<td>
<label for="file">
<i class="fa fa-upload" id="hello" aria-hidden="true" >
</i>
</label>
<input type="file" name="files[{{$index}}].File" id="file" />
<input type="text" name="files[{{$index}}].Name" id="Name" />
<input type="text" name="files[{{$index}}].Id" id="Id" />
</td>
</tr>
</table>
<button type="submit" >Upload All</button>
}
</div>
and in your action
public ActionResult AddAuto(List<UploadFiles> files)
{
foreach (var file in files)
{
// here you can access properties e.g file.File
}
}
I am trying to submit dynamic form data to spring controller using ajax so that i could save list of object later to the database. Everything is set but i am not able to handle dynamic form data in the ajax part. The problem is how to create the javascript object for each row of table and post those objects as JSON data.
All the code is like this:
HTML
<html>
<head>
<title>Add Students</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="form-group">
<form id="student_detail" name="student_detail">
<table class="table table-bordered" id="student_dynamic_table">
<tr>
<td><input type="text" name="name[]" id="name" placeholder="Enter Name" class="form-control name_list" /></td>
<td><input type="text" name="age[]" id="age" placeholder="Enter Age" class="form-control age_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">+</button></td>
<tr>
</table>
<input type="button" class="btn btn-info" id="submit" name="submit" value="Submit" />
</form>
</div>
</div>
</body> </html>
JS
$(document).ready(function(){
var i=0;
$('#add').click(function(){
i++;
$('#student_dynamic_table').append('<tr id="row'+i+'"> <td><input type="text" name="name[]" id="name'+i+'" placeholder="Enter Name" class="form-control name_list" /></td><td><input type="text" name="age[]" id="age'+i+'" placeholder="Enter Age" class="form-control age_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">x</button></td><tr>');
});
$(document).on('click','.btn_remove', function(){
var button_id=$(this).attr("id");
//id of the clicked button
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
var url= "${pageContext.request.contextPath}";
var student = ({
name : $('#name').val(),
age : $('#age').val()
});
$.ajax({
type : "POST",
url : url + '/submitDynamicForm',
data:JSON.stringify( student),
dataType : 'json',
contentType : 'application/json',
success : function(response)
{
}
}); }); });
Controller
#Autowired
private StudentDao studentDao;
#RequestMapping(value = "/dynamic", method = RequestMethod.GET)
public ModelAndView geDynamicForm() {
ModelAndView form = new ModelAndView("dynamicform");
return form;
}
#RequestMapping(value = "/submitDynamicForm", method = RequestMethod.POST)
public void saveUser(#RequestBody List<Student> student) {
studentDao.insertListOfStudent(student);
} }
Model
#Entity
public class Student {
#Id
#GeneratedValue
private Long id;
#Column(name = "name")
private String name;
#Column(name = "age")
private int age;
// getters setters
}
Hibernate to insert list of students
#Transactional
public void insertListOfStudent(List<Student> student) {
Session session = sessionFactory.getCurrentSession();
for(Student std : student) {
session.save(std);
}
Thank You in advance
var totalRow=$('#student_dynamic_table tr').length; // last row count
var data={}; //object
for (i = 0; i < totalRow; i++) {
data[$("#row"+i).val()] = $("#age"+i).val(); // adding value to data object which will be in key value format({"ram:"21","hari":"25"})
}
data: { "jsonData": JSON.stringify(data) }, // on your ajax data submit
so now in you controller you can get the data with .key() and .value() but make sure you parse with JSON.parse before .