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

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

Related

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;
}
}

Pass last created id from action to a partial view (asp.net mvc)

I have a little problem that I'm stuck on. I have 2 tables: tbl_NIR and tbl_I_O,
tbl_I_O has a foreign key NirID, so I know which nir got that i_o.
I have an action Add and view, there I insert nir data into the database. Add action returns PartialView. In that PartialView I have new view for tbl_I_O.
I need to somehow get the last ID inserted which I should somehow get after I insert data in Add action. How can you pass ID from Add action to tbl_I_O partial view? I viewed this link and others but with no luck: "Asp.Net mvc - pass last created id from action to partial view".
Actions:
[HttpPost]
public ActionResult Add(BOL1.tbl_NIR nir)
{
try
{
if (ModelState.IsValid)
{
db.tbl_NIR.Add(nir);
db.SaveChanges();
//var ni = db.tbl_NIR.OrderByDescending(x => x.ID).FirstOrDefault().ID;
TempData["Msg"] = "Created Successfully!";
return RedirectToAction("AddIO", nir);
//return RedirectToAction("AddIO", new { id = ni });
//return RedirectToAction("AddIO", "AddIO", new { id = ni });
}
return View(nir);
and the ohter:
[HttpGet]
public ActionResult AddIO()
{
//var ni = db.tbl_I_O.OrderByDescending(x => x.NirID).FirstOrDefault().NirID;
//return View(ni);
return View();
}
[HttpPost]
public ActionResult AddIO(BOL1.tbl_I_O oi)
//public ActionResult AddIO(BOL1.tbl_I_O oi, int ID)
{
try
{
if (ModelState.IsValid)
{
db.tbl_I_O.Add(oi);
db.SaveChanges();
TempData["Msg"] = "Created Successfully!";
return RedirectToAction("Index");
}
return View(oi);
}
and this is the part of code from my view where I need to display the last inserted ID from tbl_NIR (action Add) to tbl_I_O (action AddIO partial view):
<div class="form-group">
#Html.LabelFor(model => model.NirID, "Nir ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownList("NirID", null, htmlAttributes: new { #class = "form-control" })*#
#Html.EditorFor(model => model.NirID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NirID, "", new { #class = "text-danger" })
</div>
</div>
So any help on it is really appriciated. Sorry for any bad spelling!
Here is my update on this (the view and the partial view):
#model BOL1.tbl_NIR
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#*#{int i = 0;}*#
<div class="form-horizontal">
<h2>Add New</h2>
<br />
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Number, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Number, new { htmlAttributes = new { #class = "form-control" } })
#*<span>#(++i)</span>*#
#Html.ValidationMessageFor(model => model.Number, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Date, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Date, "", 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>
}
#*I 'ved commented this section because it displays the partial view in the same view as VIEW (Add controller) and I don't want that, I want them to be on separate views.*#
#*<div class="form-group">
#Html.Partial("AddIO", new BOL1.tbl_I_O())
</div>*#
<div>
#Html.ActionLink(" Back to List", "Index", null, new { #class = "glyphicon glyphicon-chevron-left" })
</div>
and the partial view:
#model BOL1.tbl_I_O
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<br />
<h5>Add new Entry or Exit</h5>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.NirID, "Nir ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownList("NirID", null, htmlAttributes: new { #class = "form-control" })*#
#Html.EditorFor(model => model.NirID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NirID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TipID, "Type ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownListFor(model => model.TipID, (IEnumerable<SelectListItem>)ViewBag.TID, new { #class = "form-control" })*#
#Html.EditorFor(model => model.TipID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TipID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SupplierID, "Supplier ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownListFor(model => model.SupplierID, (IEnumerable<SelectListItem>)ViewBag.SID, new { #class = "form-control" })*#
#Html.EditorFor(model => model.SupplierID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SupplierID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductID, "Product ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownListFor(model => model.ProductID, (IEnumerable<SelectListItem>)ViewBag.PID, new { #class = "form-control" })*#
#Html.EditorFor(model => model.ProductID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EntryDate, "Entry Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EntryDate, new { htmlAttributes = new { #class = "form-control" } })
#*<input class="datefield" data-val="true" id="EntryDate" name="EntryDate" type="date" value=" " />*#
#Html.ValidationMessageFor(model => model.EntryDate, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.ExitDate, "Exit Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ExitDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ExitDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<font color="#D3D1D1">
#Html.LabelFor(model => model.Quantity, htmlAttributes: new { #class = "control-label col-md-2" })
</font>
<div class="col-md-10">
#Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { #class = "form-control" } })
#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" } })
#Html.ValidationMessageFor(model => model.Price, "", new { #class = "text-danger" })
</div>
</div>
#*<div class="form-group">
#Html.LabelFor(model => model.Total, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Total, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Total, "", 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", null, new { #class = "glyphicon glyphicon-chevron-left" })
</div>
Basically what I need is, when I create the new row for tbl_NIR (e.g.: ID = 23 (autoincrement), blah blah), the value from the ID ("23") to be displayed in the partial view on the:
#Html.EditorFor(model => model.NirID, new { htmlAttributes = new { #class = "form-control" } })
field. I think that maybe the "EdidorFor is the problem"!?
You cannot redirect to PartialView.
[HttpPost]
public ActionResult Add(BOL1.tbl_NIR nir)
{
if (ModelState.IsValid)
{
db.tbl_NIR.Add(nir);
db.SaveChanges();
Session["id"]=nir.ID;
return RedirectToAction("AddIO");
}
return View(nir);
}
C# -pass a new BOL1.tbl_I_O object.
[HttpGet]
public ActionResult AddIO()
{
return View(new BOL1.tbl_I_O());
}
HTML
Change
#Html.EditorFor(model => model.NirID, new { htmlAttributes = new { #class = "form-control" } })
To
<input type="text" id="NirID" name="NirID" class="form-control" value="#Session["id"]"/>

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!

html.beginForm post null value for List<strongly typed> to controller via jQuery Ajax function in ASP>NET-MVC5

I have ASP.net-mvc5 website. I need to allow user update/ edit two emergency contact details. To achieve that I am sending "list myModel" to razor view and in view I got two #html.beginform. I have List because I know I always have two record. I am printing value from list via index 0 for record 1 and 1 for record 2. Jquery Ajax function used to post data back to controller.
Now form 1 for emergency contact detail 1 is working fine but form 2 for 2nd emergency contact detail posting null values to controller. I have commet form1 and tried to submit form2 but still null values. I am not sure why this happening.
Controller
[Authorize]
[HttpGet]
public ActionResult EditEmergencyContact()
{
int _studentEntityID = 0;
_studentEntityID = _studentProfileServices.GetStudentIDByIdentityUserID(User.Identity.GetUserId());
List<EmergencyContact> _emergencyContactModel = new List<EmergencyContact>();
_emergencyContactModel = _studentProfileServices.GetEmergencyContactByStudentID(_studentEntityID);
return PartialView("EditEmergencyContact_Partial", _emergencyContactModel);
}
[Authorize]
[HttpPost]
public ActionResult EditEmergencyContact(List<EmergencyContact> _emergencyContactModel)
{
try
{
if (_emergencyContactModel!=null && _emergencyContactModel.Count()>0)
{
if (ModelState.IsValid)
{
int _entityID = _studentProfileServices.EditEmergencyContactByStudentID(
new EmergencyContact
{
EmergencyContactID = _emergencyContactModel[0].EmergencyContactID,
StudentID = _emergencyContactModel[0].StudentID,
NameOfContact = _emergencyContactModel[0].NameOfContact,
Relationship = _emergencyContactModel[0].Relationship,
Telephone = _emergencyContactModel[0].Telephone,
Mobile = _emergencyContactModel[0].Mobile,
Address = _emergencyContactModel[0].Address
});
if (_entityID != 0)
{
return Json(new { Response = "Success" });
}
else
{
return Json(new { Response = "Error" });
}
}
else
{
return Json(new { Response = "Invalid Entry" });
}
}
else
{
return Json(new { Response = "Error! In Updating Record" });
}
}
catch (DataException ex)
{
ModelState.AddModelError("", "Unable To Edit Emergency Contact" + ex);
}
return RedirectToAction("MyProfile", "StudentProfile");
}
View
#using (Html.BeginForm("EditEmergencyContact", "StudentProfile", FormMethod.Post, new { id = "EditNo2EmergencyContactForm" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Emergency Contact 2</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model[1].EmergencyContactID)
<div class="form-group">
#Html.LabelFor(model => model[1].StudentID, "StudentID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].StudentID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].StudentID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].NameOfContact, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].NameOfContact, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].NameOfContact, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].Relationship, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].Relationship, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].Relationship, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].Telephone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].Telephone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].Telephone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].Mobile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].Mobile, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].Mobile, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
Jquery Function
$('#EditNo2EmergencyContactForm').submit(function (e) {
e.preventDefault();
var formURL = $(this).attr("action");
alert($(this).serialize());
$.ajax({
url: formURL,
type: "POST",
data: $(this).serialize()
}).done(function (data, textStatus, jqXHR) {
if (data.Response == "Success") {
$(this).MyMessageDialog({
_messageBlockID: "_StatusMessage",
_messageContent: "Record Been Updated Successfully",
_messageBlockWidth: "300px"
});
$('div#_StatusMessage').on('dialogclose', function (event) {
window.location = "/StudentProfile/MyProfile";
});
}
else {
$(this).MyMessageDialog({
_messageBlockID: "_StatusMessage",
_messageContent: "<div class='errorMessage'>" + data.Response + "</div>",
_messageBlockWidth: "300px"
});
}
}).fail(function (jqXHR, textStatus, errorThrown) {
$(this).MyMessageDialog({
_messageBlockID: "_StatusMessage",
_messageContent: "<div class='errorMessage'> Error In Updating Record! " + textStatus + " " + errorThrown + " "+jqXHR.status +"</div>",
_messageBlockWidth: "350px"
});
$('div#_StatusMessage').on('dialogclose', function (event) {
window.location = "/StudentProfile/MyProfile";
});
});
});
For Form 1: this one works
#using (Html.BeginForm("EditEmergencyContact", "StudentProfile", FormMethod.Post, new { id = "EditNo1EmergencyContactForm" }))
..............
$('#EditNo1EmergencyContactForm').submit(function (e) {
You are using same controller post action for different forms.
Your action update model (list of entities) only entity present on first position.
Your models has a list of [entity0, entity1] but in form view you remove entity0 because you are binding only one entity1 from model having list.
Here you have 2 approaches:
Make post controller action more generic
public ActionResult EditEmergencyContact (List<EmergencyContact> _emergencyContactModel)
{
try
{
if (_emergencyContactModel != null && _emergencyContactModel.Count() > 0)
{
if (ModelState.IsValid)
{
bool validation = true;
for (int i = 1; i < _emergencyContactModel.Count(); i++)
{
if (_emergencyContactModel[i].EmergencyContactID != null)
{
int _entityID = _studentProfileServices.EditEmergencyContactByStudentID(
new EmergencyContact
{
EmergencyContactID = _emergencyContactModel[i].EmergencyContactID,
StudentID = _emergencyContactModel[i].StudentID,
NameOfContact = _emergencyContactModel[i].NameOfContact,
Relationship = _emergencyContactModel[i].Relationship,
Telephone = _emergencyContactModel[i].Telephone,
Mobile = _emergencyContactModel[i].Mobile,
Address = _emergencyContactModel[i].Address
});
if (_entityID == 0)
{
validation = false;
break;
}
}
}
if (validation)
{
return Json(new { Response = "Success" });
}
else
{
return Json(new { Response = "Error" });
}
}
else
{
return Json(new { Response = "Invalid Entry" });
}
}
else
{
return Json(new { Response = "Error! In Updating Record" });
}
}
catch (DataException ex)
{
ModelState.AddModelError("", "Unable To Edit Emergency Contact" + ex);
}
return RedirectToAction("MyProfile", "StudentProfile");
}
Option 2, do not pass model empty entities to controller, hide inside the form the values:
#using (Html.BeginForm("EditEmergencyContact", "StudentProfile", FormMethod.Post, new { id = "EditNo2EmergencyContactForm" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Emergency Contact 2</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#* here you pas List 0 model recieved value and viceversa if you edit model[0]*#
#Html.HiddenFor(model => model[0].EmergencyContactID)
#Html.HiddenFor(model => model[0].StudentID)
#Html.HiddenFor(model => model[0].NameOfContact)
#Html.HiddenFor(model => model[0].Relationship)
#Html.HiddenFor(model => model[0].Telephone)
#Html.HiddenFor(model => model[0].Mobile)
#Html.HiddenFor(model => model[0].Address)
#Html.HiddenFor(model => model[0].Address)
#Html.HiddenFor(model => model[1].EmergencyContactID)
<div class="form-group">
#Html.LabelFor(model => model[1].StudentID, "StudentID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].StudentID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].StudentID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].NameOfContact, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].NameOfContact, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].NameOfContact, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].Relationship, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].Relationship, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].Relationship, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].Telephone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].Telephone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].Telephone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].Mobile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].Mobile, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].Mobile, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model[1].Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model[1].Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model[1].Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
the controller where you update both entities from list :
int _entityID_0 = _studentProfileServices.EditEmergencyContactByStudentID(
new EmergencyContact
{
EmergencyContactID = _emergencyContactModel[0].EmergencyContactID,
StudentID = _emergencyContactModel[0].StudentID,
NameOfContact = _emergencyContactModel[0].NameOfContact,
Relationship = _emergencyContactModel[0].Relationship,
Telephone = _emergencyContactModel[0].Telephone,
Mobile = _emergencyContactModel[0].Mobile,
Address = _emergencyContactModel[0].Address
});
int _entityID_1 = _studentProfileServices.EditEmergencyContactByStudentID(
new EmergencyContact
{
EmergencyContactID = _emergencyContactModel[1].EmergencyContactID,
StudentID = _emergencyContactModel[1].StudentID,
NameOfContact = _emergencyContactModel[1].NameOfContact,
Relationship = _emergencyContactModel[1].Relationship,
Telephone = _emergencyContactModel[1].Telephone,
Mobile = _emergencyContactModel[1].Mobile,
Address = _emergencyContactModel[1].Address
});
if (_entityID_0 != 0 && _entityID_1 != 0)
{
return Json(new { Response = "Success" });
}
else
{
return Json(new { Response = "Error" });
}
Your approach is very bad, you should update address one by one not a complex list of address.

Categories

Resources