I'm in VS 2013 and am completely new to ASP.NET MVC in general. I have been attempting to do this for sometime with no luck. Have a user complete a form with an image upload, and have that form with the image written to the DB. I know its best to write the path to the DB and store the image in the content folder of the application but I have no idea how to do any of this. Can someone give me a starting point?
I also have a ClientUtility.cs that is used to populate drop-downs but I don't see this being needed right now.
Currently the data type for the image ref in the db is VARCHAR(255).
Controller:
private TpsEntities db = new TpsEntities();
[HttpPost]
public ActionResult SaveStaffDetails(RegisterStaffViewModel model)
{
var staff = new staffTable()
{
staffFirstName = model.FirstName,
staffLastName = model.LastName,
staffTitle = model.SelectedTitle,
staffAddress = model.Address,
staffCity = model.City,
staffState = model.SelectedState,
staffZip = model.ZipCode,
staffExperience = model.SelectedExperience,
staffEducation = model.SelectedEducation,
desiredSalary = model.SelectedSalary,
staffProfession = model.SelectedProfession,
staffAvailibity = model.SelectedAvailability,
staffEmail = model.EmailAddress,
staffPhoneNum = model.PhoneNumber,
staffPhoto = null,
userID = model.UserId
};
using (var db = new TpsEntities())
{
db.staffTables.Add(staff);
db.SaveChanges();
}
var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
var user = userManager.FindById(model.UserId);
userManager.AddToRole(model.UserId, "Staff");
ClaimsIdentity identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
identity.AddClaim(new Claim(ClaimTypes.Role, "Staff"));
var AuthenticationManager = System.Web.HttpContext.Current.GetOwinContext().Authentication;
AuthenticationManager.SignIn(new AuthenticationProperties() {IsPersistent = false}, identity);
return RedirectToAction("Index", "Home");
}
}
ViewModel:
public class RegisterStaffViewModel
{
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[Display(Name = "Address")]
public string Address { get; set; }
public System.Web.UI.WebControls.ListItemCollection Title { get; set; }
[Required]
[Display(Name = "Title")]
public string SelectedTitle { get; set; }
[Required]
[Display(Name = "City")]
public string City { get; set; }
public System.Web.UI.WebControls.ListItemCollection States { get; set; }
[Required]
[Display(Name = "State")]
public string SelectedState { get; set; }
[Required]
[Display(Name = "Zip Code")]
public double? ZipCode { get; set; }
[Required]
[Phone]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email Address")]
public string EmailAddress { get; set; }
public System.Web.UI.WebControls.ListItemCollection Experience { get; set; }
[Required]
[Display(Name = "Experience")]
public string SelectedExperience { get; set; }
public System.Web.UI.WebControls.ListItemCollection Education { get; set; }
[Required]
[Display(Name = "Education")]
public string SelectedEducation { get; set; }
public System.Web.UI.WebControls.ListItemCollection Salary { get; set; }
[Required]
[Display(Name = "Salary")]
public string SelectedSalary { get; set; }
public System.Web.UI.WebControls.ListItemCollection Profession { get; set; }
[Required]
[Display(Name = "Profession")]
public string SelectedProfession { get; set; }
public System.Web.UI.WebControls.ListItemCollection Availability { get; set; }
[Required]
[Display(Name = "Availability")]
public string SelectedAvailability { get; set; }
public string UserId { get; set; }
}
View:
#*Start of Registration Form for Staff*#
#using (Html.BeginForm("SaveStaffDetails", "Staff", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(m => m.UserId)
<fieldset>
<!-- Form Name -->
<legend>Register New Staff</legend>
#*First Name*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.FirstName, new { #class = "form-control input-md", #placeholder = "First Name" })
</div>
</div>
#*Last Name*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.LastName, new { #class = "form-control input-md", #placeholder = "Last Name" })
</div>
</div>
#*Person Title*#
<div class="form-group">
<label class="col-md-6 control-label" for="title">Title</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedTitle, new SelectList(Model.Title, "Text", "Value"))
</div>
</div>
#*Address Line*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.Address, new { #class = "form-control input-md", #placeholder = "Address" })
</div>
</div>
#*City*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.City, new { #class = "form-control input-md", #placeholder = "City" })
</div>
</div>
#*State*#
<div class="form-group">
<label class="col-md-6 control-label" for="state">State</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedState, new SelectList(Model.States, "Text", "Value"))
</div>
</div>
#*Zip Code*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.ZipCode, new { #class = "form-control input-md", #placeholder = "Zip Code" })
</div>
</div>
#*Phone Number*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.PhoneNumber, new { #class = "form-control input-md", #placeholder = "Phone Number" })
</div>
</div>
#*Email Address*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.EmailAddress, new { #class = "form-control input-md", #placeholder = "Email Address" })
</div>
</div>
#*Experience*#
<div class="form-group">
<label class="col-md-6 control-label" for="experience">Experience</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedExperience, new SelectList(Model.Experience, "Text", "Value"))
</div>
</div>
#*Education*#
<div class="form-group">
<label class="col-md-6 control-label" for="education">Education</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedEducation, new SelectList(Model.Education, "Text", "Value"))
</div>
</div>
#*Desired Salary*#
<div class="form-group">
<label class="col-md-6 control-label" for="salary">Desired Salary</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedSalary, new SelectList(Model.Salary, "Text", "Value"))
</div>
</div>
#*Profession*#
<div class="form-group">
<label class="col-md-6 control-label" for="profession">Profession</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedProfession, new SelectList(Model.Profession, "Text", "Value"))
</div>
</div>
#*Availability*#
<div class="form-group">
<label class="col-md-6 control-label" for="availability">Availability</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedAvailability, new SelectList(Model.Availability, "Text", "Value"))
</div>
</div>
<!-- INSERT IMAGE UPLOAD HERE -->
</fieldset>
<input type="submit" value="Save" />
}
Edit your controller as the following code.I assumed that staffPhoto is taking picturepath.
public ActionResult SaveStaffDetails(RegisterStaffViewModel model,HttpPostedFileBase image)
{
if (Request.Files.Count > 0) {
string FileName = Guid.NewGuid().ToString().Replace("-", "");
string Path = System.IO.Path.GetExtension(Request.Files[0].FileName);
string FullPath = "~/Images/StaffPhotos/" + FileName + Path;
Request.Files[0].SaveAs(Server.MapPath(FullPath));
staffPhoto = FileName + Path;
}
}
In your view you need a file post input
<input type="file" class="filestyle" name="image" data-classbutton="btn btn-primary" data-input="false">
Related
I'm trying to save data from the view to the database from one main view and 1 partial view. Here AppRequest is the main class and the others are Purchase, PurchasingEmpl, PurchasingItems.
But when I debug the code, to the controller AppRequest main view data will pass but other class data not showing. Also not passing to the other tables also. Can you help me with this?
These are my model classes:
public class AppRequest
{
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "Request Type")]
public int ReqType { get; set; }
[Required]
[Display(Name = "Requesting By")]
public int Req_By { get; set; }
[Required]
[Display(Name = "Requesting Date")]
public DateTime Req_Date { get; set; } = DateTime.Now;
[Required]
[Display(Name = "Request Location")]
public int Req_Location { get; set; }
[Required]
[Display(Name = "Request Heading")]
public string Req_Heading { get; set; }
[Display(Name = "Cover Note")]
public string Req_CoverNote { get; set; }
[Required]
[Display(Name = "Company Name")]
public int Company_Id { get; set; }
public bool Status { get; set; }
public int Create_By { get; set; }
public DateTime Created_Date { get; set; }
public int Modified_By { get; set; }
public DateTime Modified_Date { get; set; } = DateTime.Now;
public int Approval_Status { get; set; }
public virtual IList<Purchase> Purchase { get; set; }
[NotMapped]
public Purchase PurchaseItem { get; set; }
}
#region Purchase
public class Purchase
{
[Key]
public int Id { get; set; }
[Required]
[ForeignKey("AppRequest")]
public int Req_Id { get; set; }
public virtual AppRequest AppRequest { get; set; }
public virtual IList<PurchasingEmpl> PurchasingEmpl { get; set; }
public virtual IList<PurchasingItems> PurchasingItems { get; set; }
}
public class PurchasingEmpl
{
[Key]
public int Id { get; set; }
[Required]
[ForeignKey("Purchase")]
public int Purchase_Id { get; set; }
public virtual Purchase Purchase { get; set; }
public int Emp_Id { get; set; }
public bool Status { get; set; }
}
public class PurchasingItems
{
[Key]
public int Id { get; set; }
[Required]
[ForeignKey("Purchase")]
public int Purchase_Id { get; set; }
public virtual Purchase Purchase { get; set; }
public int Supp_Id { get; set; }
public int Itm_Description_Id { get; set; }
public decimal Unit_Amount { get; set; }
public byte[] Attachment { get; set; }
public decimal Qty { get; set; }
public string Recomandation { get; set; }
public bool Status { get; set; }
public bool Settled { get; set; } = false;
public string PoNo { get; set; }
}
This is the controller
public ActionResult Create(AppRequest appRequest)
{
if (ModelState.IsValid)
{
appRequest.Create_By = int.Parse(((System.Security.Claims.ClaimsIdentity)User.Identity).FindFirst("UserId").Value);
appRequest.Created_Date = DateTime.Now;
appRequest.Modified_By= int.Parse(((System.Security.Claims.ClaimsIdentity)User.Identity).FindFirst("UserId").Value);
appRequest.Modified_Date = DateTime.Now;
appRequest.Status = true;
db.AppRequest.Add(appRequest);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(appRequest);
}
HTML View
````
#model Asp_PASMVC.Models.AppRequest
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
List<SelectListItem> ReqTypes = (List<SelectListItem>)TempData.Peek("RequestTyleList");
List<SelectListItem> Employees = (List<SelectListItem>)TempData.Peek("EmployeeList");
List<SelectListItem> Location = (List<SelectListItem>)TempData.Peek("LocationList");
List<SelectListItem> Companies = (List<SelectListItem>)TempData.Peek("ComapnyList");
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<!-- Default box -->
<div class="card">
<div class="card-header" >
<h3 class="card-title">Request Header Details</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse" title="Collapse">
<i class="fas fa-minus"></i>
</button>
<button type="button" class="btn btn-tool" data-card-widget="remove" title="Remove">
<i class="fas fa-times"></i>
</button>
</div>
</div>
<div class="card-body">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="form-group row">
#Html.LabelFor(model => model.ReqType, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.DropDownListFor(model => model.ReqType, ReqTypes, new { #class = "js-dropdown" })
#Html.ValidationMessageFor(model => model.ReqType, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="form-group row">
#Html.LabelFor(model => model.Company_Id, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.DropDownListFor(model => model.Company_Id, Companies, new { #class = "js-dropdown" })
#Html.ValidationMessageFor(model => model.Company_Id, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="form-group row">
#Html.LabelFor(model => model.Req_By, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.DropDownListFor(model => model.Req_By, Employees, new { #class = "js-dropdown" })
#Html.ValidationMessageFor(model => model.Req_By, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="form-group row">
#Html.LabelFor(model => model.Req_Location, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.DropDownListFor(model => model.Req_Location, Location, new { #class = "js-dropdown" })
#Html.ValidationMessageFor(model => model.Req_Location, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group row">
#Html.LabelFor(model => model.Req_Heading, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-6">
#Html.EditorFor(model => model.Req_Heading, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Req_Heading, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="form-group row">
#Html.LabelFor(model => model.Req_Date, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.EditorFor(model => model.Req_Date, new { htmlAttributes = new { #class = "js-datepicker" } })
#Html.ValidationMessageFor(model => model.Req_Date, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group row">
#Html.LabelFor(model => model.Req_CoverNote, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-6">
#Html.EditorFor(model => model.Req_CoverNote, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Req_CoverNote, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<!-- /.card-footer-->
</div>
<!-- /.card -->
</div>
</div>
</div>
</section>
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<!-- Default box -->
<div class="card">
<div class="card-header">
<h3 class="card-title">Request Main Details</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse" title="Collapse">
<i class="fas fa-minus"></i>
</button>
<button type="button" class="btn btn-tool" data-card-widget="remove" title="Remove">
<i class="fas fa-times"></i>
</button>
</div>
</div>
<div class="card-body">
#Html.Partial("_Purchase", Model.PurchaseItem);
<!-- /.card-body -->
<div class="card-footer">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
<!-- /.card-footer-->
</div>
<!-- /.card -->
</div>
</div>
</div>
</section>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
````
I have View with two dropdownlists first with product category and second depends on selected category list of products. When click save button and ajax redirect to Post AddOrEditPartial in controller my model object has only autogenerated Id and CreateAt. All other data from dropdowns and quantity field are null.I cant find where is the problem. Can somebody help?
public class Warehouse : BaseEntity
{
[Required(ErrorMessage = "Category Required")]
public string IdCategory { get; set; }
[Required(ErrorMessage = "Product Required")]
public string IdProduct { get; set; }
[Required(ErrorMessage = "Quantity required")]
public int Quantity { get; set; }
}
public class WarehouseViewModel
{
public Warehouse Warehouse { get; set; }
public IEnumerable<ProductCategory> ProductCategories1 { get; set; }
public IEnumerable<Product> Products { get; set; }
}
IndexView
#using (Ajax.BeginForm("AddOrEditPartial", "Warehouse", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "formsubmit", OnSuccess = "closePopUp(data)" }))
{
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Product</h4>
</div>
<div class="modal-body" id="modbody">
#Html.Partial("AddOrEditPartial")
</div>
</div>
</div>
</div>
}
PartialView
#model MyShop.Core.ViewModels.WarehouseViewModel
<div class="panel-group">
<div class="panel-default">
<div class="panel panel-success">
<div class="panel-heading">Succes Implement Add/Edit Button</div>
<div class="panel-body" id="panbody">
<div class="col-sm-12">
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Warehouse.Id)
<div class="form-group">
#Html.LabelFor(model => model.Warehouse.IdCategory, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Warehouse.IdCategory, new SelectList(Model.ProductCategories1, "Category", "Category"), "Please select Category", new { #class = "form-control" })
#*#Html.DropDownListFor(model => model.Warehouse.Category, (IEnumerable<SelectListItem>)new SelectList(ViewBag.Cat, "Category", "Category"), "Please select Category", new { #class = "form-control" })*#
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Warehouse.IdProduct, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Warehouse.IdProduct, (IEnumerable<SelectListItem>)new SelectList(ViewBag.Prod, "Name", "Name"), "Please Select Product", new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Warehouse.Quantity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Warehouse.Quantity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Warehouse.Quantity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-success" id="btnSubmit" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Warehouse_IdCategory").change(function () {
var prodId = $(this).val();
console.log(prodId);
//debugger
$.ajax({
type: "GET",
url: '#Url.Action("GetProductList", "Warehouse")/' +prodId,
data: { prodId: prodId },
contentType: "html",
success: function (response) {
//debugger
$("#Warehouse_IdProduct").empty();
$("#Warehouse_IdProduct").append(response);
}
})
})
})
</script>
Controller
public ActionResult Index()
{
WarehouseViewModel whViewModel = new WarehouseViewModel();
whViewModel.Warehouse = new Warehouse();
whViewModel.ProductCategories1 = productCategories.Collection();
whViewModel.Products = contextProduct.Collection();
return View(whViewModel);
}
[HttpPost]
public ActionResult AddOrEditPartial(Warehouse wh)
{
if (!ModelState.IsValid)
{
return Json(new { success = false });
}
else
{
var data = context.Find(wh.Id);
if (data != null)
{
data.IdProduct = wh.IdProduct;
data.IdCategory = wh.IdCategory;
data.Quantity = wh.Quantity;
context.Commit();
}
else
{
context.Insert(wh);
context.Commit();
}
return Json(new { success = true });
}
}
Change type of your IdCategory & IdProduct to int and it should work.
public class Warehouse : BaseEntity
{
[Required(ErrorMessage = "Category Required")]
public int IdCategory { get; set; }
[Required(ErrorMessage = "Product Required")]
public int IdProduct { get; set; }
[Required(ErrorMessage = "Quantity required")]
public int Quantity { get; set; }
}
#UmairZafar
public class ProductCategory : BaseEntity
{
[Required(ErrorMessage="Please fill category")]
public string Category { get; set; }
}
public class Product : BaseEntity
{
[StringLength(20)]
[DisplayName("Product Name")]
[Required(ErrorMessage = "Please fill product name")]
public string Name { get; set; }
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Range(0,1000)]
public decimal Price { get; set; }
public string Category { get; set; }
public string Image { get; set; }
}
public abstract class BaseEntity
{
public string Id { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public BaseEntity()
{
Id = Guid.NewGuid().ToString();
CreatedAt = DateTime.Now;
}
}
This question already has answers here:
Post an HTML Table to ADO.NET DataTable
(2 answers)
Closed 4 years ago.
I have this ViewModel:
public class DepositViewModel
{
public DepositViewModel()
{
DepositDate = DateTime.Now;
CollectedReceipts = new List<DepositQuantityAmountViewModel>();
CancelledReceipts = new List<DepositQuantityAmountViewModel>();
}
[Display(Name = "Deposit #")]
public long DepositId { get; set; }
[Display(Name = "Deposit Type")]
public string DepositType { get; set; }
[Display(Name = "Cashier #")]
public int CashierId { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Deposit Date")]
[DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime DepositDate { get; set; }
[Display(Name = "Collected Receipts")]
public IList<DepositQuantityAmountViewModel> CollectedReceipts { get; set; }
[Display(Name= "Cancelled Receipts")]
public IList<DepositQuantityAmountViewModel> CancelledReceipts { get; set; }
[Display(Name = "Finance Reference")]
[MaxLength(2000)]
public string FinanceReference { get; set; }
[Display(Name = "Received Amount")]
[DisplayFormat(DataFormatString = "{0:N2}", ApplyFormatInEditMode = true)]
public decimal ReceivedAmount { get; set; }
[Display(Name = "Payment Modes")]
public IList<BDOs.PayMode> PaymentModes { get; set; }
}
public class DepositQuantityAmountViewModel
{
[Display(Name = "Description")]
public string Description { get; set; }
[Display(Name = "Category")]
public string Category { get; set; }
[Display(Name = "Count")]
public int Count { get; set; }
[Display(Name = "Total")]
[DisplayFormat(DataFormatString = "{0:N2}", ApplyFormatInEditMode = true)]
public decimal Amount { get; set; }
}
In my view, I have this setup:
<div class="row">
<div class="col-sm-2">
<div class="form-group">
<fieldset>
<legend>#Html.DisplayNameFor(m => m.PaymentModes)</legend>
<div class="col-sm-12">
<div class="row">
#foreach (var modelPaymentMode in Model.PaymentModes)
{
#Html.DisplayFor(m => modelPaymentMode, "_DepositPartPaymentModes")
}
</div>
</div>
</fieldset>
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<fieldset>
<legend>#Html.DisplayNameFor(m => m.CollectedReceipts)</legend>
#Html.DisplayFor(m => m.CollectedReceipts, "_DepositPartDetail")
</fieldset>
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<fieldset>
<legend>#Html.DisplayNameFor(m => m.CancelledReceipts)</legend>
#Html.DisplayFor(m => m.CancelledReceipts, "_DepositPartDetail")
</fieldset>
</div>
</div>
</div>
And here are the display templates:
_DepositPartPaymentModes.cshtml
#model DA.Services.IBS.Business.BDO.PayMode
<div class="form-group">
#Html.TextBoxFor(m => m.Name, new { #class = "form-control", #readonly = "readonly" })
</div>
_DepositPartDetail.cshtml
#model IEnumerable<DA.Services.IBS.Web.FinancePortalFull.Models.DepositQuantityAmountViewModel>
#foreach (var countAmountPair in Model)
{
if (countAmountPair.Category == "TotalCollected" || countAmountPair.Category == "TotalCancelled")
{
<div class="col-sm-12">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(m => countAmountPair.Description, new { #class = "form-control", #readonly = "readonly" })
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(m => countAmountPair.Amount, "{0:N2}", new { #class = "form-control", type = "numeric", dir = "rtl", #readonly = "readonly" })
</div>
</div>
</div>
</div>
}
else
{
<div class="col-sm-12">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(m => countAmountPair.Count, "{0:N0}", new { #class = "form-control", type = "numeric", dir = "rtl", #readonly = "readonly" })
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(m => countAmountPair.Amount, "{0:N2}", new { #class = "form-control", type = "numeric", dir = "rtl", #readonly = "readonly" })
</div>
</div>
</div>
</div>
}
}
I have tried to bind each template separately looking at different guides. I cannot get the collections to be returned to postback as they are null. They display properly all three collections are null on submission.
What am I doing wrong?
Solution
Do not use ForEach Loops in views to iterate collections. Use For Loops.
The issue is in using foreach loops. When this is rendered in HTML, the input elements are not given names that will mean anything to the model binder when you post. You need to change these to for loops and the inputs will be rendered correctly.
You may also need to change your model so that the list is not null when the binder is trying to add to it.
Eg:
#for (int i = 0; i < Model.PaymentModes; i++)
{
#Html.DisplayFor(m => Model.PaymentModes[i], "_DepositPartPaymentModes")
}
Use for loop instead of foreach.
Element should be like this.
<input type="text" name="List[0].PropertyName" value="XYZ" />
change #model IEnumerable<DA.Services.IBS.Web.FinancePortalFull.Models.DepositQuantityAmountViewModel> to #model List<DA.Services.IBS.Web.FinancePortalFull.Models.DepositQuantityAmountViewModel>
_DepositPartDetail.cshtml
for (int i=0;i<Model.Count(); i++)
{
{
if (countAmountPair.Category == "TotalCollected" || countAmountPair.Category == "TotalCancelled")
{
<div class="col-sm-12">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(m => m[i].Description, new { #class = "form-control", #readonly = "readonly" })
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(m => m[i].Amount, "{0:N2}", new { #class = "form-control", type = "numeric", dir = "rtl", #readonly = "readonly" })
</div>
</div>
</div>
</div>
}
else
{
<div class="col-sm-12">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(m => m[i].Count, "{0:N0}", new { #class = "form-control", type = "numeric", dir = "rtl", #readonly = "readonly" })
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(m => m[i].Amount, "{0:N2}", new { #class = "form-control", type = "numeric", dir = "rtl", #readonly = "readonly" })
</div>
</div>
</div>
</div>
}
}
I have implemented Required validation for my MVC view. The text controls show the validation message but the kendo combobox doesnt. I'm doing an ajax postback.
Any reason why the comboxbox doest show the message? The work Type combo is mandatory, but its not showing the validation message.
View
#using (Ajax.BeginForm("ActivityWorkLog_Create", "Activity", new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "OnWorklogStatusSuccess",
OnFailure = "OnWorklogStatusFailure"
}, new { id = "workLogForm" }))
{
<div class="k-popup-edit-form k-window-content k-content" data-role="window">
<div class="k-edit-form-container">
#Html.HiddenFor(x => x.RequestID, new { data_bind = "value: requestId" })
#Html.HiddenFor(x => x.ActivityID, new { data_bind = "value: activityId" })
#Html.HiddenFor(x => x.CountryCode, new { data_bind = "value: countryCode" })
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.WorkLogAppliesToName)
</div>
<div class="editor-field">
#(Html.Kendo().ComboBoxFor(model => model.WorkLogAppliesToName)
.Name("WorkLogAppliesToID")
.Filter("contains")
.HtmlAttributes(new { style = "width:300px", #readonly = "readonly" })
.Placeholder("Select...")
.DataTextField("WorkLogAppliesToName")
.DataValueField("WorkLogAppliesToID")
.DataSource(dataSource => dataSource
.Read(read => read.Action("GetWorkLogAppliesTo", "WorkLog", new { id = 0 }).Type(HttpVerbs.Post)
)
)
)
#Html.ValidationMessageFor(model => model.WorkLogAppliesToName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.ActivitySLA)
</div>
<div class="editor-field">
#*#Html.EditorFor(model => model.ActivitySLA)*#
#Html.TextBoxFor(model => model.ActivitySLA, new { id = "ActivityDesc", #readonly = "readonly", Class = "textBoxFor" })
</div>
</div>
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.ActivityID)
</div>
<div class="editor-field">
#(Html.Kendo().ComboBoxFor(model => model.ActivityID)
.Name("Activity")
.Filter("contains")
.HtmlAttributes(new { style = "width:300px", #readonly = "readonly" })
.Placeholder("Select...")
.DataTextField("Description")
.DataValueField("ActivityID")
.DataSource(dataSource => dataSource
.Read(read => read.Action("GetActivity", "WorkLog").Data("additionalActivityInfo").Type(HttpVerbs.Post)
)//.ServerFiltering(true)
)//.CascadeFrom("ServiceID").Filter("contains")
)
#Html.ValidationMessageFor(model => model.ServiceID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.WorkLogType)
</div>
<div class="editor-field">
#(Html.Kendo().ComboBoxFor(model => model.WorkLogTypeCode)
.Name("WorkLogTypeCode1")
.Filter("contains")
.HtmlAttributes(new { style = "width:300px"})
.Placeholder("Select...")
.DataTextField("WorkLogType")
.DataValueField("WorkLogTypeCode")
.DataSource(dataSource => dataSource
.Read(read => read.Action("GetWorkLogType", "WorkLog").Data("additionalWLTInfo").Type(HttpVerbs.Post))
)
)
#Html.ValidationMessageFor(model => model.WorkLogTypeCode, "Please select a worklog type", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.WorkLogSubject)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.WorkLogSubject)
#Html.ValidationMessageFor(model => model.WorkLogSubject, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.WorkLogDetails)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.WorkLogDetails, new { htmlAttributes = new { #class = "form-control", cols = "50" } })
#Html.ValidationMessageFor(model => model.WorkLogDetails, "", new { #class = "text-danger" })
</div>
</div>
<div class="worklogStatusButtonAlign">
<button id="btnWorkLogSave" type="submit" class="k-button k-button-icontext k-primary k-grid-update">Save</button>
<button id="btnClose" type="button" class="k-button k-button-icontext k-grid-cancel">Cancel</button>
</div>
<div id="worklogStatusMessage"> </div>
</div>
</div>
}
Javacript
<script>
$(document).ready(function () {
var form = $("#workLogForm")
.removeData("validator")
.removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(form);
});
View model
public class ActivityWorkLogViewModel
{
[ScaffoldColumn(false)]
[Display(Name = "WorkLogID", ResourceType = typeof(Resources.Resource))]
public int WorkLogID { get; set; }
[Required(ErrorMessage = "WorkLogType is required")]
[Display(Name = "WorkLogTypeCode", ResourceType = typeof(Resources.Resource))]
public string WorkLogTypeCode { get; set; }
[Display(Name = "WorkLogType", ResourceType = typeof(Resources.Resource))]
public string WorkLogType { get; set; }
[Required]
[Display(Name = "WorkLogAppliesToID", ResourceType = typeof(Resources.Resource))]
public int WorkLogAppliesToID { get; set; }
[Display(Name = "WorkLogAppliesToName", ResourceType = typeof(Resources.Resource))]
public string WorkLogAppliesToName { get; set; }
[Required]
[Display(Name = "RequestID", ResourceType = typeof(Resources.Resource))]
public int RequestID { get; set; }
[Display(Name = "ServiceID", ResourceType = typeof(Resources.Resource))]
public Nullable<int> ServiceID { get; set; }
[Display(Name = "ActivityID", ResourceType = typeof(Resources.Resource))]
public Nullable<int> ActivityID { get; set; }
[Required(ErrorMessage = "Subject is required")]
[Display(Name = "WorkLogSubject", ResourceType = typeof(Resources.Resource))]
public string WorkLogSubject { get; set; }
[Required(ErrorMessage = "Details is required")]
[Display(Name = "WorkLogDetails", ResourceType = typeof(Resources.Resource))]
public string WorkLogDetails { get; set; }
[Display(Name = "EmailTo", ResourceType = typeof(Resources.Resource))]
public string EmailTo { get; set; }
[Display(Name = "IsActive", ResourceType = typeof(Resources.Resource))]
public bool IsActive { get; set; }
[Display(Name = "CountryCode", ResourceType = typeof(Resources.Resource))]
public string CountryCode { get; set; }
[Display(Name = "ActivitySLA", ResourceType = typeof(Resources.Resource))]
public string ActivitySLA { get; set; }
}
Try to add this:
<script>
$(function () {
$("form").kendoValidator();
});
</script>
and/or:
<script>
$.validator.setDefaults({
ignore: ""
});
</script>
You can set validation rules to force the a item selection:
$("form").kendoValidator({
rules: {
invalidSelection: function (input) {
if (input.is("[name=COMBO_NAME]")) {
if (input.val() != "" && $("#TCOMBO_NAME").data("kendoComboBox").selectedIndex == -1) {
return false;
}
}
return true;
}
}
});
This way it travel all the fields of the form, being able to establish rules for each field. Regards.
I have a partial view that returns a list of users address's, I need the user to be able to select one, then when they press "submit" along with the other details it takes the details from the selected address returns it to the controller, from there I know how to assign it where I want. How would I do this? Examples and help appreciated
Here is my controller for creating the order, view beneath;
[HttpPost]
public ActionResult AddressAndPayment(FormCollection values, string id)
{
var order = new Order();
TryUpdateModel(order);
//sets date and username
order.Username = User.Identity.Name;
order.OrderDate = DateTime.Now;
//Order gets saved
storeDB.Orders.Add(order);
storeDB.SaveChanges();
//Order gets processed
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.CreateOrder(order);
//Save again, total not saving properly until now
storeDB.SaveChanges();
return RedirectToAction("Complete",
new { id = order.OrderId });
}
VIEW
#model T_shirt_Company_v3.Models.Order
#{
ViewBag.Title = "Address And Payment";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.HiddenFor(x => x.OrderId)
#Html.HiddenFor(x => x.OrderDate)
#Html.HiddenFor(x => x.PaymentTransactionId)
#Html.HiddenFor(x => x.Total)
#Html.HiddenFor(x => x.Username)
<div class="form-horizontal">
<h2>Address And Payment</h2>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#{Html.RenderAction("Listofaddresses", "Checkout");}
<h2>Select Postage type</h2>
#Html.EnumDropDownListFor(model => model.PostageList, "-- Please select postage type --")
<h2>Payment</h2>
<div class="form-group">
#Html.LabelFor(model => model.cardDetails.FullName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.cardDetails.FullName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.cardDetails.FullName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.cardDetails.CardNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.cardDetails.CardNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.cardDetails.CardNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.cardDetails.CardExpireMonth, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="row">
<div class="col-md-1">
#Html.EditorFor(model => model.cardDetails.CardExpireMonth, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.cardDetails.CardExpireMonth, "", new { #class = "text-danger" })
</div>
<div class="col-md-1">
#Html.EditorFor(model => model.cardDetails.CardExpireYear, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.cardDetails.CardExpireYear, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.cardDetails.Cvc, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.cardDetails.Cvc, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.cardDetails.Cvc, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Partial View
#model IEnumerable<T_shirt_Company_v3.Models.deliveryAddress>
#foreach (var item in Model)
{
<div style="width: 180px">
<div class="thumbnail">
<p>#Html.DisplayFor(modelItem => item.FirstName) #Html.DisplayFor(modelItem => item.LastName) </p>
<p>#Html.DisplayFor(modelItem => item.Address)</p>
<p>#Html.DisplayFor(modelItem => item.City)</p>
<p>#Html.DisplayFor(modelItem => item.PostalCode)</p>
<p>#Html.DisplayFor(modelItem => item.Country)</p>
</div>
</div>
}
Address Class
public class deliveryAddress
{
[Key]
[ScaffoldColumn(false)]
public int AdressId { get; set; }
[ScaffoldColumn(false)]
public string UsersAddress { get; set; }
[Required]
[StringLength(16, ErrorMessage = "Your name is too long")]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Your last name is required.")]
[StringLength(16, ErrorMessage = "Last name is too long.")]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required(ErrorMessage = "Address is required.")]
public string Address { get; set; }
[Required(ErrorMessage = "City is required.")]
public string City { get; set; }
[Required(ErrorMessage = "Postcode is required.")]
[Display(Name = "Post Code")]
public string PostalCode { get; set; }
[Required(ErrorMessage = "Country is required.")]
public string Country { get; set; }
[Required(ErrorMessage = "Phone home number is required.")]
[Display(Name = "Home Telephone")]
public string Phone { get; set; }
[Required(ErrorMessage = "Phone mobile number is required.")]
[Display(Name = "Mobile")]
public string Mobile { get; set; }
}
}