I know that the question was asked and answered many times, but unfortunately no one of the answers helped me.
I have tree POCO models, which are Pharmacy, Address and Company gathered together into a ViewModel PharmacyVM:
public class PharmacyVM
{
public Pharmacy pharmacyProp { get; set; }
public Address addressProp { get; set; }
public Company companyProp { get; set; }
public int CityId { get; set; }
public PharmacyVM()
{
pharmacyProp = new Pharmacy();
addressProp = new Address();
companyProp = new Company();
}
}
Don't laugh at the properties names; at the start, they had been normal (Address, Company and Pharmacy) I changed them according to one of the lots of answers in here, but... it didn't help :(
In the Get action of the Create method I'm trying to manually create the PharmacyVM object and pass it to the view:
public ActionResult Create()
{
ViewBag.CityId = new SelectList(db.Cities, "Id", "Name");
ViewBag.CompanyId = new SelectList(db.Companies, "Id", "Name");
ViewBag.AddressId = new SelectList(db.Addresses, "Id", "Name");
ViewBag.CityId = new SelectList(db.Cities, "Id", "Name");
ViewBag.RegionId = new SelectList(db.Regions, "Id", "Name");
ViewBag.DistrictId = new SelectList(db.Districts, "Id", "Name");
ViewBag.MicrodistrictId = new SelectList(db.Microdistricts, "Id", "Name");
ViewBag.StreetId = new SelectList(db.Streets, "Id", "Name");
ViewBag.VillageId = new SelectList(db.Villages, "Id", "Name");
var pharmacyVM = new PharmacyVM();
return View(pharmacyVM);
}
There is a standard Razor code in the view:
#model MEDONET.Models.PharmacyVM
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm("Create", "Pharmacies", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>pharmacyProp</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.companyProp, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CompanyId", null, "", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.companyProp.Id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.pharmacyProp.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.pharmacyProp.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.pharmacyProp.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.addressProp.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CityId", null, "", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CityId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CityId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CityId", null, "", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CityId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.addressProp.Village, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("VillageId", null, "", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.addressProp.VillageId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.addressProp.District, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("DistrictId", null, "", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.addressProp.DistrictId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.HiddenFor(model => model.addressProp.RegionId)
#Html.LabelFor(model => model.addressProp.Region, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("RegionId", null, "", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.addressProp.RegionId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.addressProp.Microdistrict, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("MicrodistrictId", null, "", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.addressProp.MicrodistrictId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.addressProp.Building, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.addressProp.Building, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.addressProp.Building, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.addressProp.Street, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("MicrodistrictId", null, "", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.addressProp.MicrodistrictId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.pharmacyProp.IsGov, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.pharmacyProp.IsGov)
#Html.ValidationMessageFor(model => model.pharmacyProp.IsGov, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.companyProp, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("companyId", null, "", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.pharmacyProp.CompanyId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.pharmacyProp.LargeImage, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="LargeImageFile" required />
</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>
}
<div> #Html.ActionLink("Back to List", "Index")</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
And then in the Post action of the Create method, I'm trying to create b and c variables:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PharmacyVM model, HttpPostedFileBase LargeImageFile)
{
if (ModelState.IsValid)
{
string LargeImageFileName = Path.GetFileNameWithoutExtension(LargeImageFile.FileName);
string LargeImageExtansion = Path.GetExtension(LargeImageFile.FileName);
LargeImageFileName = LargeImageFileName + DateTime.Now.ToString("yymmssfff") + LargeImageExtansion;
LargeImageFileName = Path.Combine(Server.MapPath("~/Images/Pharmacy/Banners/"), LargeImageFileName);
int b = model.CityId;
int c = model.addressProp.RegionId.Value;
//Address address = new Address()
//{
// Id = 12,//db.Addresses.AsEnumerable().Last().Id + 1,
// RegionId = PharmacyVM.Address.RegionId,
// DistrictId = PharmacyVM.Address.DistrictId,
// CityId = PharmacyVM.Address.CityId,
// MicrodistrictId = PharmacyVM.Address.MicrodistrictId,
// StreetId = PharmacyVM.Address.StreetId,
// VillageId = PharmacyVM.Address.VillageId,
// Building = PharmacyVM.Address.Building,
// Cab = PharmacyVM.Address.Cab
//};
//Address address = new Address
//{
// Id = 12,//db.Addresses.AsEnumerable().Last().Id + 1,
// RegionId = 1,
// DistrictId = 1,
// CityId = 1,
// MicrodistrictId = 1,
// StreetId = 1,
// VillageId = 1,
// Building = "1",
// Cab = "1"
//};
//db.Addresses.Add(address);
db.SaveChanges();
var pharmacy = new Pharmacy
{
Name = model.pharmacyProp.Name,
//AddressId = address.Id,
IsGov = model.pharmacyProp.IsGov,
CompanyId = model.pharmacyProp.CompanyId,
LargeImage = "~/Images/Pharmacy/Banners/" + LargeImageFileName
};
LargeImageFile.SaveAs(LargeImageFileName);
db.Pharmacies.Add(pharmacy);
db.SaveChanges();
ModelState.Clear();
return RedirectToAction("Index");
}
}
Unlike first variable b, the second one c is gonna be null because the addressProp property is null.
So why is it so strange? How can I use ViewModel without duplicating original model's fields?
why are you use
int b= model.addressProp.RegionId.Value
instead of
int b=model.addressProp.RegionId
Even for your good cording the best and good way is remove all View bag and
Add all View bag properties to PharmacyVM Class
Dont use two properties for view binding
Example
public class PharmacyVM
{
public Pharmacy pharmacyProp { get; set; }
public Address addressProp { get; set; }
public Company companyProp { get; set; }
public int CityId { get; set; }
public SelectList CityIdList { get; set; }
public PharmacyVM()
{
pharmacyProp = new Pharmacy();
addressProp = new Address();
companyProp = new Company();
CityIdList =new SelectList(db.Cities, "Id", "Name");
}
}
public ActionResult Create()
{
var pharmacyVM = new PharmacyVM();
return View(pharmacyVM);
}
#model PharmacyVM
#using (Html.BeginForm())
{
#Html.HiddenFor(m => m.CityId )
<div class="editor-label">
#Html.LabelFor(m => m.Name)
</div>
<div class="editor-field">
#Html.EditorFor(m => m.Name)
#Html.ValidationMessageFor(m => m.Name)
</div>
<button type="submit">Create</button>
}
[HttpPost]
public ActionResult Create(PharmacyVM model)
{
int c = model.addressProp
return View(viewModel);
}
More Information
Related
I have a Course Table and a Hole Table in SQL. There is a foreign Key in the hole Table that is set to the CourseId.
This is so that when I create a hole I can assign it to the relevant course.
In my View I have a dropdownlistfor that has a list of courses to select from when creating the hole. However when I try and post back the values the courseID does not post back.
HoleViewModel
// GET: HoleViewModels/Create
public ActionResult Create()
{
var dbcourse = db.Course.ToList();
//Make selectlist, which is IEnumerable<SelectListItem>
var courseNameDropdownList = new SelectList(db.Course.Select(item => new SelectListItem()
{
Text = item.CourseName.ToString(),
Value = item.CourseId.ToString()
}).ToList(), "Value", "Text");
// Assign the Selectlist to the View Model
var viewCourse = new HoleViewModel()
{
Course = dbcourse.FirstOrDefault(),
// The Dropdownlist values
CourseNamesDropdownList = courseNameDropdownList,
};
return View(viewCourse);
}
// POST: HoleViewModels/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "HoleId,HoleNumber,Par,Length,StrokeIndex,CourseId")] HoleViewModel holeViewModel)
{
if (ModelState.IsValid)
{
db.HoleViewModels.Add(holeViewModel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(holeViewModel);
}
The Create.cshtml
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>HoleViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.HoleNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HoleNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HoleNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Par, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Par, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Par, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Length, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Length, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Length, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StrokeIndex, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StrokeIndex, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StrokeIndex, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Course.CourseId, "CourseId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Course.CourseId, Model.CourseNamesDropdownList, "Please select from List", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CourseId, "", new { #class = "text-danger" })
</div>
</div>
So when the holeview posts back holeNumber, Par, Length, StrokeIndex, CourseID. it passes all data into the hole table other than the courseId which it posts a null.
What am I missing from the POST to get the CourseId to be entered in the Database.
Am new to stripe asp.net mvc payment
[HttpPost]
[Route("/Purchase")]
public ActionResult Purchase(string stripeEmail, string stripeToken,int amount, Customer customer)
{
if (ModelState.IsValid)
{
var stripecustomers = new StripeCustomerService();
var charges = new StripeChargeService();
Customer c = new Customer
{
FirstName = customer.FirstName,
LastName = customer.LastName,
Email = customer.Email,
Phone = customer.Phone,
Address = customer.Address,
City = customer.City,
State = customer.State,
PostalCode = customer.PostalCode,
Country = customer.Country
};
Order o = new Order
{
OrderDate = DateTime.Now,
DeliveryDate = DateTime.Now.AddDays(5),
CID = c.CID
};
db.Customers.Add(c);
db.Orders.Add(o);
foreach (var i in db.ShoppingCartDatas.ToList<ShoppingCartData>())
{
db.Order_Products.Add(new Order_Products
{
OrderID = o.OrderID,
PID = i.PID,
Qty = i.Quantity,
TotalSale = i.Quantity * i.UnitPrice
});
db.ShoppingCartDatas.Remove(i);
}
db.SaveChanges();
var stripecustomer = stripecustomers.Create(new StripeCustomerCreateOptions {
Email = stripeEmail,
SourceToken = stripeToken
});
var charge = charges.Create(new StripeChargeCreateOptions {
// Amount 500 equals to $5.00
Amount = amount,
Description = "Test Site",
Currency = "usd",
CustomerId = stripecustomer.Id
});
double adjamt = amount;
adjamt = adjamt/100;
ViewBag.Amount = adjamt;
return View();
}
return View(customer);
}
and my Payment view
<h2>Purchase</h2>
#using (Html.BeginForm("Purchase", "Checkout", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Phone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Phone, new { htmlAttributes = new { #class = "form-control", #type = "number" } })
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.City, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.State, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.State, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.State, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PostalCode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PostalCode, new { htmlAttributes = new { #class = "form-control", #type = "number" } })
#Html.ValidationMessageFor(model => model.PostalCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Country, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Country, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Country, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<p>Total: #String.Format("{0:c}", ViewBag.CartTotalPrice)</p>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
#{
decimal sum = ViewBag.CartTotalPrice;
decimal amount = sum * 100;
int adjamt = (int)amount;
}
<script src="//checkout.stripe.com/v2/checkout.js"
class="stripe-button"
data-key="pk_test_key"
data-locale="auto"
data-description="test Site"
data-amount=#adjamt>
</script>
</div>
</div>
</div>
}
Stripe capture the payment, on clicking the pay button on stripe payment, i will get the following error on postback.
The parameters dictionary contains a null entry for parameter 'amount' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Purchase(System.String, System.String, Int32, AllPlus.Models.Customer)' in 'AllPlus.Controllers.CheckoutController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
I am trying to populate a dropdownlist and then post it to db but for some reason it is giving error, please advice.
Controller
public class StudentController : BaseController
{
private List<SelectListItem> _gendersList;
[HttpGet]
public ActionResult Create()
{
var model = new CreateStudent();
_gendersList = new List<SelectListItem>()
{
new SelectListItem { Text = Constants.Gender.Boy, Value = Constants.Gender.Boy},
new SelectListItem { Text = Constants.Gender.Girl, Value = Constants.Gender.Girl},
};
model.Genders = _gendersList;
return View(model);
}
[HttpPost]
public ActionResult Create(CreateStudent student)
{
var result = true;
_gendersList = new List<SelectListItem>()
{
new SelectListItem { Text = Constants.Gender.Boy, Value = Constants.Gender.Boy},
new SelectListItem { Text = Constants.Gender.Girl, Value = Constants.Gender.Girl},
};
if (ModelState.IsValid)
{
result = _student.Insert(mappedStudent);
if (result)
{
return RedirectToAction("Index");
}
else
{
TempData["Message"] = "Failed to create new student";
return View();
}
}
return View("Create");
}
}
View
#model CreateStudent
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery-3.1.1.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<h2>Create</h2>
#{
if (TempData["Message"] != null)
{
<h3>
#TempData["Message"].ToString()
</h3>
}
}
#{
}
#using (Html.BeginForm("Create","Student",FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MiddleName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.MiddleName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MiddleName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Gender, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownListFor(o=>o.Gender,Model.StudentGender, "", new { #class = "form-control" })*#
#Html.DropDownListFor(o=>o.Gender,(List<SelectListItem>)Model.Genders,"1", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Gender, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IdNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.IdNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.IdNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SchoolIdNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SchoolIdNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SchoolIdNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ServiceType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ServiceType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ServiceType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Comments, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Comments, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Comments, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IsEnabled, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.IsEnabled)
#Html.ValidationMessageFor(model => model.IsEnabled, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstNameAr, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstNameAr, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstNameAr, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MiddleNameAr, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MiddleNameAr, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MiddleNameAr, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastNameAr, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastNameAr, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastNameAr, "", 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-primary" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Your view is strongly typed to a CreateStudent class and the view code is using Model.Genders collection property when you use the DropDownListFor helper method. But in your http post action, you are calling the return View() method without passing a valid CreateStudent object and in another case without populating the Genders property. So when razor executes the view code, the model value is null ( because you did not pass anything to the view)
You need to set the Genders property again before returning the posted view model back to the view.
[HttpPost]
public ActionResult Create(CreateStudent student)
{
var genderList = new List<SelectListItem>()
{
new SelectListItem { Text = Constants.Gender.Boy, Value = Constants.Gender.Boy},
new SelectListItem { Text = Constants.Gender.Girl, Value = Constants.Gender.Girl},
};
if (ModelState.IsValid)
{
var result = _student.Insert(mappedStudent);
if (result)
{
return RedirectToAction("Index");
}
else
{
student.Genders = genderList;
TempData["Message"] = "Failed to create new student";
return View(student); // Passing the object here to view
}
}
//Model validation fails. Return the same view
student.Genders = genderList;
return View(student);
}
}
Also there no need for an extra casting. Model.Genders is of type List<SelectListItem>
#Html.DropDownListFor(o=>o.Gender,Model.Genders, new { #class = "form-control" })
I would want to insert multiple entries in my table called 'sibling' using it's Create Method (which I generated automatically using Scaffolding methods). I already made the form dynamic in adding the fields. However, when I click on the Submit button it only gets the first entry.
I sort of have an idea by implementing 'foreach' in the said method but I can't seem to find an answer that is spot on. Especially for my case I just want to modify the Create Method for 'sibling' which was generated automatically (if there is such a way without having to create a new method - but if not I am fine with a different approach as well).
This is my SiblingController:
public ActionResult Create(int id)
{
var sib = new sibling();
sib.child_id = id;
return View(sib);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "sibling_id,child_id,age,gender")] sibling sibling)
{
if (ModelState.IsValid)
{
db.siblings.Add(sibling);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.child_id = new SelectList(db.children, "child_id", "last_name", sibling.child_id);
return View(sibling);
}
This is my Create.cshtml for Sibling:
#model dummyApp.Schema.TestModels.sibling
#{
ViewBag.Title = "Create";
}
#section Scripts{
<script type="text/javascript">
//Coding
$("#numBox").change(function () {
var htmlString = "";
var len = $(this).val();
for (var i = 0; i < len; i++) {
htmlString += ' <div class="form-group">\
#Html.LabelFor(model => model.child_id, "child_id", htmlAttributes: new { #class = "control-label col-md-2" })\
<div class="col-md-10">\
#Html.EditorFor(model => model.child_id, new { htmlAttributes = new { #class = "form-control" }})\
#Html.ValidationMessageFor(model => model.child_id, "", new { #class = "text-danger" })\
</div>\
</div>\
<div class="form-group">\
#Html.LabelFor(model => model.age, htmlAttributes: new { #class = "control-label col-md-2" })\
<div class="col-md-10">\
#Html.EditorFor(model => model.age, new { htmlAttributes = new { #class = "form-control" } })\
#Html.ValidationMessageFor(model => model.age, "", new { #class = "text-danger" })\
</div>\
</div>\
<div class="form-group">\
#Html.LabelFor(model => model.gender, htmlAttributes: new { #class = "control-label col-md-2" })\
<div class="col-md-10">\
#Html.EditorFor(model => model.gender, new { htmlAttributes = new { #class = "form-control" } })\
#Html.ValidationMessageFor(model => model.gender, "", new { #class = "text-danger" })\
</div>\
</div>\
';
}
$("#adtnl_fields").html(htmlString);
})
</script>
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>sibling</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<!--
<div class="form-group">
#Html.LabelFor(model => model.sibling_id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.sibling_id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.sibling_id, "", new { #class = "text-danger" })
</div>
</div>
-->
<div class="form-group">
#Html.Label("Number of Siblings:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="number" id="numBox" class="form-control"/>
</div>
</div>
<!--
<div class="form-group">
#Html.LabelFor(model => model.child_id, "child_id", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*Html.DropDownList("child_id", null, htmlAttributes: new { #class = "form-control" })*#
#Html.EditorFor(model => model.child_id, new { htmlAttributes = new { #class = "form-control" }})
#Html.ValidationMessageFor(model => model.child_id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.age, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.age, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.age, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.gender, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.gender, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.gender, "", new { #class = "text-danger" })
</div>
</div>
-->
<!-- Div for additional fields -->
<div id="adtnl_fields">
</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>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
This is my 'sibling.cs':
public partial class sibling
{
public int sibling_id { get; set; }
public int child_id { get; set; }
public Nullable<int> age { get; set; }
public string gender { get; set; }
public virtual child child { get; set; }
}
Please help. Thank you!
You can use AddRange method in EF-6
IList<Student> newStudents = new List<Student>();
newStudents.Add(new Student() { StudentName = "Student1 by addrange" });
newStudents.Add(new Student() { StudentName = "Student2 by addrange" });
newStudents.Add(new Student() { StudentName = "Student3 by addrange" });
using (var context = new SchoolDBEntities())
{
context.Students.AddRange(newStudents);
context.SaveChanges();
}
As the title says, I'am trying to write an algoritm with these conditions:
Each employee has a flextime balance which is initially zero.
If the total time of all stamp ins and stamp outs in a working day exceeds 8 hours, the flexitime balance listed with the prolonged time , and the same principle applies to the deficit.
Flextime balance is listed with all the time stamped on the days that are relieved of work.
If no stamps occurred on a working day then the flextime balance is not affected.
There are two tables im having in the database: NonWorkingDays and Stampings.
NonWorkingDays contains only of one column which is: "Days (DateTime)".
Stampings contains of four columns: "Id (Int) (PK), UserId (Int), Timestamp (DateTime), StampingType (value "in" and value "out")
This is what I wrote so far -
Model:
public class FlexModel
{
public List<User> Users { get; set; }
public List<Stamping> Stampings { get; set; }
public decimal FlexTime { get; set; }
}
View:
#model Aviato.ViewModel.FlexModel
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h2>Info</h2>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Users[0].UserId)
#Html.HiddenFor(model => model.Users[0].SocialSecurityNumber)
#Html.HiddenFor(model => model.Users[0].FirstName)
#Html.HiddenFor(model => model.Users[0].LastName)
#Html.HiddenFor(model => model.Users[0].EmploymentStartDate)
#Html.HiddenFor(model => model.Users[0].EmploymentEndDate)
#Html.HiddenFor(model => model.Users[0].Password)
#Html.HiddenFor(model => model.Users[0].RoleName)
<div class="form-group">
#Html.LabelFor(model => model.Users[0].Address1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Users[0].Address1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Users[0].Address1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Users[0].Address2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Users[0].Address2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Users[0].Address2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Users[0].ZipCode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Users[0].ZipCode, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Users[0].ZipCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Users[0].City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Users[0].City, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Users[0].City, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Users[0].PhoneNumber1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Users[0].PhoneNumber1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Users[0].PhoneNumber1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Users[0].PhoneNumber2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Users[0].PhoneNumber2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Users[0].PhoneNumber2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FlexTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model => model.FlexTime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FlexTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Spara" class="btn btn-default" />
</div>
</div>
</div>
}
Controller:
public ActionResult Info()
{
var flexModel = new FlexModel();
var userId = (int)Session["userId"];
var user = _db.Users.Find(userId);
var stampIn = _db.Stampings.Where(i => i.StampingType == "in").Where(i => i.User == user).ToList();
var stampOut = _db.Stampings.Where(i => i.StampingType == "out").Where(i => i.User == user).ToList();
var workDay = 8;
if (stampIn.Count == 0)
{
return View();
}
foreach (var itemIn in stampIn)
{
}
foreach (var itemOut in stampOut)
{
}
return View();
}
[HttpPost]
public ActionResult Info(FlexModel model)
{
if (ModelState.IsValid)
{
foreach (var item in model.Users)
{
_db.Entry(item).State = EntityState.Modified;
}
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
So this is not working for me, I get the value of Flex to display 0.
Help would be appreciated!