How to multiply values of two textboxes in Asp.net MVC - c#

I have 3 textboxes, 1st for Quantity, 2nd for Price and 3rd for Total Price.
<div class="form-group">
#Html.LabelFor(model => model.quantity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.quantity, new { htmlAttributes = new { #class = "form-control", #type = "number" } })
#Html.ValidationMessageFor(model => model.quantity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.price, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.price, new { htmlAttributes = new { #class = "form-control", #type = "number" } })
#Html.ValidationMessageFor(model => model.price, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.totalprice, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.totalprice, new { htmlAttributes = new { #class = "form-control", #type = "number" } })
#Html.ValidationMessageFor(model => model.totalprice, "", new { #class = "text-danger" })
</div>
and here is the controller:
[HttpPost]
public ActionResult Add(Model model)
{
obj.Quantity = model.quantity;
obj.Price = model.price;
obj.TotalPrice = model.totalprice
db.Details.Add(obj);
db.SaveChanges();
return RedirectToAction("");
}
now I want to multiply values of 1st and 2nd textboxes and show them in 3rd textbox. For example if users enter 5 in 1st textbox and 100 in 2nd textbox then it automatically shows 500 in 3rd textbox and if users changes value of 1st or 2nd textbox then value of 3rd textbox should also change accordingly.
Thanks.

You can listen to the keyup event of the textboxes in javascript, read the value and do the multiplication and set the resulting value to the third textbox.
Assuming your have jQuery library included in your page.
$(function(){
$("#quantity,#price").keyup(function(e){
var q=$("#quantity").val();
var p=$("#price").val();
var result="";
if(q!=="" && p!=="" && $.isNumeric(q) && $.isNumeric(p))
{
result = parseFloat(q)*parseFloat(p);
}
$("#totalPrice").val(result);
});
});
Here is a working jsbin sample.

You can use this:
[HttpPost]
public ActionResult Add(Model model)
{
obj.Quantity = model.quantity;
obj.Price = model.price;
obj.TotalPrice = model.totalprice
model.totalprice = model.quanity * model.price
db.Details.Add(obj);
db.SaveChanges();
return RedirectToAction("");
}
Hope it helps. I used it in my application and it does the right thing.

Related

ASP.Net MVC sending new Object to view fills some fields with bad data

I asked a question yesterday about how to fix a sudden and unexpected "Object not set to an instance of an object" error. The only real answer I got was to pass a new instance of the object to the view like this:
// GET: WC_Inbox/Create
public ActionResult Create(int? id)
{
System.Diagnostics.Debug.WriteLine("Employee ID was: " + id);
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Employee employee = db.Employees.Find(id);
if (employee == null)
{
return HttpNotFound();
}
string fullName = employee.First_Name + " " + employee.Last_Name;
System.Diagnostics.Debug.WriteLine("Employee full name: " + fullName);
ViewBag.EmployeeID = id;
ViewBag.Name = fullName;
ViewBag.Status = "Pending";
return View(new WC_Inbox());
}
With the primary line in question being here: return View(new WC_Inbox());
This worked, however it has created further issues. Now on my create page I am given some incorrect data in some fields
The fields Org Number, Hire Date, Work Schedule, and Injury date should not show those values. Those are incorrect and will be very confusing to the mostly elderly client bass the app is intended for. I would like for the placeholder values to show up there rather than this incorrect data.
This is the code from the Create view for those fields:
<div class="form-group">
#Html.LabelFor(model => model.Org_Number, "Org Number", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Org_Number, new { htmlAttributes = new { #class = "form-control", placeholder = "0025" } })
#Html.ValidationMessageFor(model => model.Org_Number, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Hire_Date, "Hire Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Hire_Date, new { htmlAttributes = new { #class = "form-control", placeholder = "8/3/2021" } })
#Html.ValidationMessageFor(model => model.Hire_Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Job_Title, "Job Title", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Job_Title, new { htmlAttributes = new { #class = "form-control", placeholder = "Programmer Analyst" } })
#Html.ValidationMessageFor(model => model.Job_Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Work_Schedule, "Work Schedule", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Work_Schedule, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Work_Schedule, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Injury_Date, "Injury Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Injury_Date, new { htmlAttributes = new { #class = "form-control", placeholder = "8/14/2021" } })
#Html.ValidationMessageFor(model => model.Injury_Date, "", new { #class = "text-danger" })
</div>
</div>
How can I get rid of that bad data and use the placeholder values I assigned instead?
PS: Work Schedule should simply be blank. There is no placeholder value.
The issue is that you are passing a default object to the strongly-typed view. On the line:
return View(new WC_Inbox());
you have not done anything to initialize the properties/values on the WC_Inbox object. This means that all the values will be the default value (0 for int, null for string, the minimum date time for DateTime, etc.) It is those default values that you are seeing on your view. If you would like blank default values, you just have to update the WC_Inbox class to support nullable types. This works because null values display as blanks, so your placeholder text will show up. For example, it worked as expected for Job_Title since Job_Title is a string and its default value is null which is then displayed as a blank by EditorFor which allows the placeholder text to display. Hopefully that makes sense - it is simple, but verbose to explain.
If your WC_Inbox class can allow for nullable values, update it and then your placeholders would work. So the class now looks like:
class WC_Inbox
{
public int? Org_Number {get; set;}
public DateTime? Hire_Date { get; set;}
public string Job_Title {get; set;} // string is nullable already
public DateTime? Work_Schedule {get; set;}
public DateTime? Injury_Date {get; set;}
}
If you update the definition of WC_Inbox then the code as you have it will work.

how can i make Html. Begin Form() work using MVC

hello i am developing a web site using MVC in order to insert data into my data base i created method called chekout like below in my HomeController:
public ActionResult chekout()
{
return View(Tuple.Create<Commande,IEnumerable< Panier >, LoginViewModel> (new Commande(), db.Paniers.ToList(), new LoginViewModel()));
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult chekout([Bind(Include = "prenom,nom,Adresse,telephone,cart")] Commande commande)
{
if (ModelState.IsValid)
{
try
{
commande.Id_commande = db.Commandes.Max().Id_commande + 1;
var panier = from Panier in db.Paniers
select Panier;
var userEmail = this.User.Identity.Name;
panier = panier.Where(x => x.user.Contains(userEmail));
foreach (var item in panier)
{
commande.produit = item.Quantite + " X " + item.nom_produit;
commande.prix = int.Parse(item.prix) * item.Quantite;
commande.Email = userEmail;
db.Commandes.Add(commande);
db.SaveChanges();
}
return RedirectToAction("order_complete", "Home");
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
Console.ReadKey();
}
}
return RedirectToAction("chekout", "Home");
}
}
then i created the form in the view chekout like this :
#using (Html.BeginForm("chekout", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Item1.prenom, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Item1.prenom, new { htmlAttributes = new { #class = "form-control", required = "required", title = "veuillez remplir ce champ" } })
#Html.ValidationMessageFor(model => model.Item1.prenom, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Item1.nom, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Item1.nom, new { htmlAttributes = new { #class = "form-control", required = "required", title = "veuillez remplir ce champ" } })
#Html.ValidationMessageFor(model => model.Item1.nom, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Item1.Adresse, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Item1.Adresse, new { htmlAttributes = new { #class = "form-control", required = "required", title = "veuillez remplir ce champ" } })
#Html.ValidationMessageFor(model => model.Item1.Adresse, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Item1.telephone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Item1.telephone, new { htmlAttributes = new { #class = "form-control", required = "required", title = "veuillez remplir ce champ" } })
#Html.ValidationMessageFor(model => model.Item1.telephone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Item1.cart, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Item1.cart, new { htmlAttributes = new { #class = "form-control", required = "required", title = "veuillez remplir ce champ" } })
#Html.ValidationMessageFor(model => model.Item1.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>
}
this is my page after i insert my data i click on commander it suppose to insert data into my database then move on the order_complete page but it id not it wipe up my data an redirect to the same page like this
but it did not work and i can not know why when i click on the button it take me back redirect to the same page without inserting data to my database
i would be grateful if anyone can help me

Can't save data into multiple tables using ASP.NET EF6

On a page on my website a person can change information about a device.
This data comes from 2 different tables. Saving data into the DeviceStatus table is no problem.
But for some reason I can't save the Active field into the concremodeDevice table. Saving all other data from this table is no problem.
Code:
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "id,DeviceConfig_id,Device_statustypes_id,ConcremoteDevice_id,Employee_1,Employee_2,Sign_Date,Active")] DeviceStatus deviceStatus, ConcremoteDevice concremoteDevice)
{
var Conn = (from d in db.DeviceStatus
join s in db.Device_statustypes on d.Device_statustypes_id equals s.id
join b in db.ConcremoteDevice on d.ConcremoteDevice_id equals b.id
join c in db.DeviceConfig on d.DeviceConfig_id equals c.Device_config_id
select new { s.id, Model = d.id });
if (ModelState.IsValid)
{
db.Entry(deviceStatus).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
// ViewBag.device_type_id = new SelectList(db.DeviceType, "device_type_id", "device_type", concremoteDevice.id);
return View(deviceStatus);
}
Page:
#model ConcremoteDeviceManagment.Models.DeviceStatus
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ConcremoteDevice</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.id)
#Html.HiddenFor(model => model.DeviceConfig_id)
#Html.HiddenFor(model => model.Device_statustypes_id)
<div class="form-group">
#Html.Label("Serie nummer", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ConcremoteDevice_id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ConcremoteDevice_id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Device Type", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model => model.DeviceConfig.DeviceType.name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DeviceConfig.DeviceType.name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Config ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DeviceConfig.Device_config_id, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.Label("Medewerker 1", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Medewerker 2", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Signeer datum", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Sign_Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Sign_Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Huidige status", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("StatusList", null, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Device_Statustypes.name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("In Gebruik", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="col-md-10 checkbox">
#Html.EditorFor(model => model.ConcremoteDevice.Active)
#Html.ValidationMessageFor(model => model.ConcremoteDevice.Active, "", new { #class = "text-danger" })
</div>
</div>
</div>
Table:
CREATE TABLE [dbo].[ConcremoteDevice] (
[id] NVARCHAR (50) NOT NULL,
[Active] BIT NULL,
CONSTRAINT [PK_ConcremoteDevice] PRIMARY KEY CLUSTERED ([id] ASC) WITH (FILLFACTOR = 65)
);
So my question is if someone knows why I can't save Active.
As suggested by pinkfloydx33 in the comments I have at some point also tried to set the state of concremodeDevice, but this gave me the next error:
The key field 'id' cannot have a value of null. A non-null value is required for the key fields defined on type 'ConcremoteDevice'
BTW, don't know if ASP.NET of EF6 has anything to do with this, but included it just to be sure.
Try the following:
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "id,DeviceConfig_id,Device_statustypes_id,ConcremoteDevice_id,Employee_1,Employee_2,Device_statustypes_id,Sign_Date,Active")] DeviceStatus deviceStatus, ConcremoteDevice concremoteDevice)
{
if (ModelState.IsValid)
{
db.Entry(deviceStatus).State = EntityState.Modified;
db.Entry(concremoteDevice).State = EntityState.Modified;
db.SaveChanges();
TempData["AlertMessage"] = "Device Edited Successfully";
return RedirectToAction("Index");
}
return View(deviceStatus);
}
And view:
<div class="form-horizontal">
<h4>ConcremoteDevice</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.id)
#Html.HiddenFor(model => model.DeviceConfig_id)
#Html.HiddenFor(model => model.Device_statustypes_id)
#Html.HiddenFor(model => model.ConcremoteDevice.id)

Edit/Update in Asp.net mvc

When I click OK, it doesn't update the record but rather redirects to the other page without the updated having been shown. What is happening now is that it would return blank; not even showing the record that was entered at initial stage. What I was trying to achieve is when the user clicks OK, redirect to the page with the updated record.
Form
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Issue</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<fieldset>
<div class="form-horizontal">
#Html.LabelFor(model => model.item.itemNumber, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.TextBoxFor(model => model.item.itemNumber, null, new { #id = "itemNumber", #class = "form-control", #readonly = "readonly", })
#Html.ValidationMessageFor(model => model.item.itemNumber, "", new { #class = "text-danger" })
#Html.LabelFor(model => model.expense_acccount, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.item.expense_account.index, new SelectList(Model.accountlist, "Value", "Text"), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.expense_acccount, "", new { #class = "text-danger" })
</div>
#Html.LabelFor(model => model.item.price, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.TextBoxFor(model => model.item.price, new { #id = "price", #class = "form-control", #readonly = "readonly", })
#Html.ValidationMessageFor(model => model.item.price, "", new { #class = "text-danger" })
#Html.LabelFor(model => model.item.quantity, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.item.quantity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.item.quantity, "", new { #class = "text-danger" })
<input type="submit" value="OK" name="OK" class="btn btn-default" />
<input type="button" value="Cancel" name="Cancel" onclick="location.href='#Url.Action("IssueItem","Issue")' " class="btn btn-default" />
Controller
public ActionResult Edit(int id)
{
getIssue.item = getIssue.items[id - 1]; //Returns the requested item for editing
return View(getIssue);
}
public ActionResult Edit(Issue issue)
{
int indx = issue.item.lineNum - 1;
getIssue.items[indx] = issue.item;
return RedirectToAction("IssueItem");
}
public ActionResult IssueItem()
{
Session.Clear();
IssueDAO dbData = new IssueDAO();
getIssue.docNumber = string.Concat("IS", DateTime.Now.ToString("yymmddhhmmss"));
getIssue.docType = "Issue"; getIssue.inventory_acccount = 5520; ViewBag.StoresReps = dbData.SelectEmployeesByDept("Stores");
getIssue.item = new Item();
return View(getIssue);
}
private Issue getIssue {
get
{
Issue issue = (Issue)Session["Issue"];
if (issue == null) { issue = new Issue();
Session["Issue"] = issue; } return issue;
}
}

Foreign Key Reference to IdentityUser Shows NULL Values (EF6/ASP.NET MVC 5)

I am trying to figure out why my model table's UserId column which references the primary key, "Id" of my AspNetUsers table (IdentityUser class in IdentityModel) is showing only NULL values when I 'Create()' an entry.
Here is the code for my two Create(), ActionResult methods in my controller class:
[Authorize]
public ActionResult Create()
{
ViewBag.UserId = new SelectList(db.Users, "Id", "Fullname");
return View();
}
// POST: Expenses/Create
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public ActionResult Create([Bind(Include = "ID,Category,Description,GrossAmount,TaxAmount,NetAmount,Mileage,MileageRate,DateSubmitted,ExpenseDate,UserId")] Expense expense)
{
if (ModelState.IsValid)
{
expense.UserId = HttpContext.Current.User.Identity.Name;
db.Expenses.Add(expense);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserId = new SelectList(db.Users, "Id", "Fullname", expense.UserId);
return View(expense);
}
Here is the code for my Create view:
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
DateTime today = DateTime.Today;
string formattedDate = today.ToString("MM/dd/yyyy");
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Expense</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.UserId, htmlAttributes: new { #Value = user, #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DateSubmitted, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DateSubmitted, new { htmlAttributes = new { #Value = formattedDate, #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DateSubmitted, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ExpenseDate, htmlAttributes: new { #Value = #formattedDate, #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ExpenseDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ExpenseDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Category, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Category, new SelectList(
new List<String>{
"Meals & Entertainment",
"Home Office",
"Travel",
"Phone",
"Auto - Mileage",
"Auto - Gas",
"Auto - Lease",
"Association Dues",
"Insurance Premium",
"Capital Assets",
"Trade Show & Promo",
"Pan Experience",
"Other"
}), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Category, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Mileage, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Mileage, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Mileage, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MileageRate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MileageRate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MileageRate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.GrossAmount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.GrossAmount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.GrossAmount, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TaxAmount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TaxAmount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TaxAmount, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NetAmount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NetAmount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NetAmount, "", 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>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section scripts {
<script type="text/javascript">
var province = 'bc';
var grossAmount = document.getElementById('GrossAmount').value;
$(function () {
$('#ExpenseDate').datetimepicker({
defaultDate: '#formattedDate',
format: 'L',
showClose: true,
showClear: true,
toolbarPlacement: 'top'
});
});
$('#DateSubmitted').prop('readonly', true);
$('#Mileage').prop('disabled', true);
$('#MileageRate').prop('disabled', true);
$(function ()
{
$('#Category').on('change',function()
{
if ($(this).val() == 'Auto - Mileage')
{
$('#Mileage').prop('disabled', false);
$('#MileageRate').prop('disabled', false);
}
else
{
$('#Mileage').prop('disabled', true);
$('#MileageRate').prop('disabled', true);
}
}
)
})
</script>
}
If you would like to take a look at my model classes, you can go this post:
How To Restrict User Entries Only to that Sepcific User in EF 6/ASP.NET MVC 5
UPDATE:
Thanks to Steve Greene for putting me on the right track and for helping me to update my Create() method to this:
public ActionResult Create()
{
ViewBag.UserId = new SelectList(db.Users, "Id", "Fullname");
return View();
}
// POST: Expenses/Create
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public ActionResult Create([Bind(Include = "ExpenseId,Category,Description,GrossAmount,TaxAmount,NetAmount,Mileage,MileageRate,DateSubmitted,ExpenseDate,UserId")] Expense expense)
{
if (ModelState.IsValid)
{
expense.UserId = System.Web.HttpContext.Current.User.Identity.Name;
db.Expenses.Add(expense);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserId = new SelectList(db.Users, "Id", "Fullname", expense.UserId);
foreach (ModelState modelState in ViewData.ModelState.Values)
{
foreach (ModelError error in modelState.Errors)
{
Response.Write(error);
}
}
Response.End();
return View(expense);
}
I don't get any major errors now, however, now ModelState.IsValid is returning False and the data I enter into Create.cshtml isn't being submitted.
I added a piece of code in the Create() method to catch the ModelState.Errors and it prints the error: System.Web.Mvc.ModelError.
I've also set a breakpoint before Create() and when I check the value of UserId, I get "null."
LAST UPDATE:
I've added a field for UserId to the Create.cshtml view and now I get the error: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Expenses_dbo.AspNetUsers_ApplicationUser_Id". The conflict occurred in database "PacificPetExpenses", table "dbo.AspNetUsers", column 'Id'.
To fix this, I modified something in my controller (please see my answer below).
Thank you.
If you are not using the UserId in the view, just set it before you add:
if (ModelState.IsValid)
{
expense.UserId = HttpContext.Current.User.Identity.Name; // or whatever
db.Expenses.Add(expense);
db.SaveChanges();
return RedirectToAction("Index");
}
Another common pattern is to add a hidden field for the UserId:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.UserId) <-- now it will post back
...
If you want to have a drop down list of users, do this:
[Authorize]
public ActionResult Create()
{
ViewBag.UserList = new SelectList(db.Users, "Id", "Fullname");
return View();
}
Then in your view add a drop down list of users:
<div class="form-group">
#Html.LabelFor(model => model.UserId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.UserId, Model.UserList, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.UserId, "", new { #class = "text-danger" })
</div>
</div>
Inside of the Create() method inside of my controller, I had the line:
expense.UserId = HttpContext.Current.User.Identity.Name;
I set up a break point and as breakpoint was on the line, it showed the correct UserId; however, after the line had executed, it showed the user's email address.
To fix this I tried changing the line above to:
expense.UserId = System.Web.HttpContext.Current.User.Identity.GetUserId();
and expenses were both being submitted with no errors and displaying in the view where it was supposed to show the list of expenses submitted by the user!

Categories

Resources