ASP.NET MVC selectlist selectedvalue not working - c#

I am using three different Selectlist to populate three different drop downs. Area, Discipline, and Shift.
The problem I am facing is that it works for the first one but not for the other two. On the form, the selectedvalue works for the area, however for discipline and shift it selects the first one on the list
List<SelectListItem> ShiftEdit = db.Shifts
.OrderBy(s => s.Site.SiteName)
.Select(s => new SelectListItem
{
Value = s.ShiftID.ToString(),
Text = s.Site.SiteName + " " + "||" + " " + s.Shift1
}).ToList();
ViewBag.ShiftEdit = new SelectList(ShiftEdit, "Value", "Text", employee.ShiftID);
List<SelectListItem> AreaEdit = db.Areas
.OrderBy(s => s.Site.SiteName)
.Select(s => new SelectListItem
{
Value = s.AreaID.ToString(),
Text = s.Site.SiteName + " " + "||" + " " + s.Area1
}).ToList();
ViewBag.AreaEdit = new SelectList(AreaEdit, "Value", "Text", employee.AreaID);
List<SelectListItem> DisciplineEdit = db.Disciplines
.OrderBy(s => s.Site.SiteName)
.Select(s => new SelectListItem
{
Value = s.DisciplineID.ToString(),
Text = s.Site.SiteName + " " + "||" + " " + s.Discipline1
}).ToList();
ViewBag.DisciplineEdit = new SelectList(DisciplineEdit, "Value", "Text", employee.DisciplineID);
The View:
<div class="form-group">
#Html.LabelFor(model => model.ShiftID, "Shift", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ShiftID", (IEnumerable<SelectListItem>)ViewBag.ShiftEdit, htmlAttributes: new { #class = "form-control", #style = "width:400px" })
#Html.ValidationMessageFor(model => model.ShiftID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AreaID, "Area", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("AreaID", (IEnumerable<SelectListItem>)ViewBag.AreaEdit, htmlAttributes: new { #class = "form-control", #style = "width:400px" })
#Html.ValidationMessageFor(model => model.AreaID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DisciplineID, "Discipline", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("DisciplineID", (IEnumerable<SelectListItem>)ViewBag.DisciplineEdit, htmlAttributes: new { #class = "form-control", #style = "width:400px" })
#Html.ValidationMessageFor(model => model.DisciplineID, "", new { #class = "text-danger" })
</div>
</div>

So I had mistakenly not deleted the original scaffoldded Viewbags which seemed to cause the problem.
I deleted them and it all works fine now

Related

DropDownListFor post value NULL to database

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.

Calling a controller Action Result method from view with an actionlink

I'm new to MVC and still figuring out how everything works. Currently, I am trying to call a method that is in my controller from my view but I'm not sure the best way to go about this. Here is my SalesOrdersController method that I want to run.
public ActionResult revertToPending(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
SalesOrder salesOrder = db.SalesOrders.Find(id);
if (salesOrder == null)
{
return HttpNotFound();
}
ViewBag.statusList = new List<Object>
{
new {value = SOStatus.Pending, text = "Pending" },
new {value = SOStatus.Released, text = "Released" },
new {value = SOStatus.Released, text = "Shipped" },
new {value = SOStatus.BackOrdered, text = "Back Ordered" },
new {value = SOStatus.Cancelled, text = "Cancelled" },
};
return View(salesOrder);
}
Here is my view
<div class="form-group">
#Html.LabelFor(model => model.SalesOrderStatus, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SalesOrderStatus, new SelectList(ViewBag.statusList, "value", "text"), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SalesOrderStatus, "", new { #class = "text-danger" })
#Html.ActionLink("Revert to Pending", "revertToPending", "SalesOrder")
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BillingStatus, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EnumDropDownListFor(model => model.BillingStatus, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.BillingStatus, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Details, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.Details, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Details, "", 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" />
</div>
</div>
And I want that to run when the user presses a button from the view.
So something like this
#Html.ActionLink("Revert to Pending", "revertToPending", "SalesOrder" )
I know that I'm doing it wrong as I don't want it to lead to the revertToPending View as it doesn't exist. But I want that controller method to run when the link is pressed.
Thanks

loop is just inserting the last row [duplicate]

This question already has answers here:
foreach returns only last item repeatedly in c sharp
(1 answer)
In a loop, is to create new object is so necessary?
(2 answers)
Closed 4 years ago.
I'm new to C# and I'm coding a web site in witch I need to insert multiple data in a row inside my database. some of the data will be set automatically and the others from form. here is my controller part:
public ActionResult chekout()
{
return View(new Commande());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult chekout([Bind(Include = "Id_commande,prenom,nom,Adresse,telephone,Email,produit,prix,cart")] Commande commande)
{
var panier = from Panier in db.Paniers
select Panier;
var userEmail = this.User.Identity.Name;
panier = panier.Where(x => x.user.Contains(userEmail));
Panier[] pa = panier.ToArray();
List<Commande> list = new List<Commande>();
for (int i = 0; i < pa.Length; i++)
{
commande.Id_commande = db.Commandes.Max(I => I.Id_commande) + 1;
commande.produit = pa[i].Quantite + " X " + pa[i].nom_produit;
commande.prix = int.Parse(pa[i].prix) * pa[i].Quantite;
commande.Email = userEmail;
list.Add(commande);
}
db.Commandes.AddRange(list);
db.SaveChanges();
return RedirectToAction("order_complete", "Home");
}
and this is my view part:
#using(Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.prenom, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.prenom, new { htmlAttributes = new { #class = "form-control", required = "required", title = "veuillez remplir ce champ" } })
#Html.ValidationMessageFor(model => model.prenom, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.nom, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.nom, new { htmlAttributes = new { #class = "form-control", required = "required", title = "veuillez remplir ce champ" } })
#Html.ValidationMessageFor(model => model.nom, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Adresse, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Adresse, new { htmlAttributes = new { #class = "form-control", required = "required", title = "veuillez remplir ce champ" } })
#Html.ValidationMessageFor(model => model.Adresse, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.telephone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.telephone, new { htmlAttributes = new { #class = "form-control", required = "required", title = "veuillez remplir ce champ" } })
#Html.ValidationMessageFor(model => model.telephone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.cart, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.cart, new { htmlAttributes = new { #class = "form-control", required = "required", title = "veuillez remplir ce champ" } })
#Html.ValidationMessageFor(model => model.cart, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type = "submit" value="Commander" class="btn btn-primary" />
</div>
</div>
}
I do not get error but I don't know why but it just adds the last row
so if anyone can help me I would be grateful.
You are adding the same commande object repeatedly in the loop, you need to instantiate new object commande in every iteration. You need to add the first line in loop below, please do change the variable name "commande" if a same name exist at class level.
for (int i = 0; i < pa.Length; i++)
{
Commande commande = new Commande ();
commande.Id_commande = db.Commandes.Max(I => I.Id_commande) + 1;
commande.produit = pa[i].Quantite + " X " + pa[i].nom_produit;
commande.prix = int.Parse(pa[i].prix) * pa[i].Quantite;
commande.Email = userEmail;
list.Add(commande);
}

Custom stripe payment in asp.net mvc 5 with optional parameter in the action controller

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.

ViewModel's parameters are null in postback

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

Categories