I get an error when adding with Fluent Validation. / When I try to validate with Fluent Validation, I get an error.
Although I submit the model, it puts it into validation when it is first opened.
Error Description:
Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: required
Error Image :
enter image description here
Added Libraries : Fluent Validation / FluentValidation.Mvc5 / FluentValidation.ValidatorAttribute 8.6.1
MVCApplication :
private void ValidationConfiguration()
{
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider
{
AddImplicitRequiredValidator = false
});
FluentValidationModelValidatorProvider.Configure(provider =>
{
provider.AddImplicitRequiredValidator = false;
provider.ValidatorFactory = new ValidatorFactory();
});
}
Class
[Table("Category")]
[Validator(typeof(CategoryValidator))]
public partial class Category
Category Validator
public class CategoryValidator:AbstractValidator<Category>
{
public CategoryValidator()
{
this.CascadeMode = CascadeMode.StopOnFirstFailure;
RuleFor(x => x.Name).NotNull().WithMessage("Boş Geçilemez");
RuleFor(x => x.Name).NotEmpty().WithMessage("Boş Geçilemez");
}
}
View
#using (Ajax.BeginForm("CategoryAddOperation", "Category", FormMethod.Post, new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "returnPostCategoryAdd(data)",
LoadingElementId = "loading-background",
},
new
{
#class = "CategoryAdd needs-validation",
#area = "Admin",
#id = "frmCategoryAdd",
#name = "frmCategoryAdd",
#enctype = "multipart/form-data",
#novalidate = "novalidate"
}))
{
#Html.AntiForgeryToken()
<div class="form-group">
#Html.LabelFor(model => model.Name)
#Html.EditorFor(model => model.Name, "", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "invalid-feedback error-validate" })
</div>
#*<div class="form-group">
#Html.LabelFor(model => model.Description)
#Html.TextAreaFor(model => model.Description, new { #class = "form-control", #spellcheck = "false" })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "invalid-feedback error-validate" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Image)
<div class="custom-file">
#Html.TextBoxFor(model => model.Images, "", new { #type = "file", #class = "custom-file-input" })
#Html.LabelFor(model => model.Image, "Resim Seçiniz", new { #class = "custom-file-label", #data_browse = "Seçiniz" })
#Html.ValidationMessageFor(model => model.Image, "", new { #class = "invalid-feedback error-validate" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Banner)
<div class="custom-file">
#Html.TextBoxFor(model => model.Banners, "", new { #type = "file", #class = "custom-file-input" })
#Html.LabelFor(model => model.Banner, "Afiş Seçiniz", new { #class = "custom-file-label", #data_browse = "Seçiniz" })
#Html.ValidationMessageFor(model => model.Banner, "", new { #class = "invalid-feedback error-validate" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Header1)
#Html.EditorFor(model => model.Header1, "", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Header1, "", new { #class = "invalid-feedback error-validate" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Header2)
#Html.EditorFor(model => model.Header2, "", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Header2, "", new { #class = "invalid-feedback error-validate" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.MainMenuId)
#Html.DropDownListFor(model => model.MainMenuId, TempData["Categories"] as List<SelectListItem>, new { #class = "custom-select" })
#Html.ValidationMessageFor(model => model.MainMenuId, "", new { #class = "invalid-feedback error-validate" })
</div>*#
}
Related
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
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;
}
}
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"]"/>
I have a view which gets username and password and needs to pass it to the Database. I can pass the username but not the password.
View:
<div class="form-group">
#Html.LabelFor(m => m.UserName, new { #class = "label-control" })
#Html.PasswordFor(m => m.UserName, new { #class = "form-control", autofocus = "", value = "Text" })
#Html.ValidationMessageFor(m => m.UserName, null, new { #class = "alert-danger" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "label-control" })
#Html.TextBoxFor(m => m.Password, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Password, null, new { #class = "alert-danger" })
</div>
Controller:
public ActionResult EditUserSubmit(string UserName, string Password, string ProcessType)
{
string process;
string name = Url.RequestContext.RouteData.Values["id"].ToString();
process = (ProcessType == "Processed") ? "P" : "B";
DB.Entities.user users = db.users.Where(m => m.username == name).FirstOrDefault();
users.password = Password;
users.processtype = process;
db.SaveChanges();
return RedirectToAction("Manager");
}
UPDATE
This is the whole View
#model NV.Tax.SST.Gateway.MVC.Models.AdministrationModel
#{string name = Url.RequestContext.RouteData.Values["id"].ToString();}
<div class="x-form-wrapper">
<div class="x-form-title">
<h3><strong>User Detail for <b>#Url.RequestContext.RouteData.Values["id"]</b></strong></h3>
</div>
<div class="x-form-body">
<div class="form-group">
#Html.LabelFor(m => m.UserName, new { #class = "label-control" })
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control", autofocus = "", value = "Text" })
#Html.ValidationMessageFor(m => m.UserName, null, new { #class = "alert-danger" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "label-control" })
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Password, null, new { #class = "alert-danger" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.ProcessType, new { #class = "label-control" })
#Html.DropDownListFor(m => m.ProcessType, new[]{
new SelectListItem { Text = "Processed", Value = "Processed" },
new SelectListItem { Text = "Both", Value = "Both" }
}, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.ProcessType, null, new { #class = "alert-danger" })
</div>
<div class="form-group">
Save
#Html.ActionLink("Cancel", "Manager", "Administration", null, new { #class = "btn btn-lg btn-default" })
</div>
</div>
</div>
#{
string password = "";
var entity = new NV.Tax.SST.Gateway.DB.Entities.sstpEntities();
var data = from db in entity.users
where db.username == name
select db;
foreach(var item in data)
{
password = item.password;
<script>document.getElementById("Password").defaultValue = "#password"</script>
if (item.processtype == "B")
{
<script>document.getElementById("ProcessType").value = "Both"</script>
}
else
{
<script>document.getElementById("ProcessType").value = "Processed"</script>
}
}
}
Since you're creating the password textbox like this
#Html.TextBoxFor(m => m.Password, new { #class = "form-control" })
It's clear that you're using a view model class that has UserName and Password property. I'd guess that it also has ProcessType property. Since you have the following syntax at the top of your view
#model NV.Tax.SST.Gateway.MVC.Models.AdministrationModel
You can use NV.Tax.SST.Gateway.MVC.Models.AdministrationModel as the parameter of your controller action method as below
public ActionResult EditUserSubmit(NV.Tax.SST.Gateway.MVC.Models.AdministrationModel model)
{
string process;
string name = Url.RequestContext.RouteData.Values["id"].ToString();
process = (model.ProcessType == "Processed") ? "P" : "B";
DB.Entities.user users = db.users.Where(m => m.username == name).FirstOrDefault();
users.password = model.Password;
users.processtype = process;
db.SaveChanges();
return RedirectToAction("Manager");
}
The value of model.Password will be what you enter in the password textbox.
EDIT
After looking at the whole view code, this is where you're wrong
Save
You can't submit the page using an anchor tag and without <form> tag. You need to have a <form> tag and a submit button inside it. The <form> tag can be generated using Html.BeginForm helper method. Change your view code to below
#model NV.Tax.SST.Gateway.MVC.Models.AdministrationModel
#{string name = Url.RequestContext.RouteData.Values["id"].ToString();}
<div class="x-form-wrapper">
<div class="x-form-title">
<h3><strong>User Detail for <b>#Url.RequestContext.RouteData.Values["id"]</b></strong></h3>
</div>
<div class="x-form-body">
#using (Html.BeginForm("EditUserSubmit", "Administration"))
{
<div class="form-group">
#Html.LabelFor(m => m.UserName, new { #class = "label-control" })
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control", autofocus = "", value = "Text" })
#Html.ValidationMessageFor(m => m.UserName, null, new { #class = "alert-danger" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "label-control" })
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Password, null, new { #class = "alert-danger" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.ProcessType, new { #class = "label-control" })
#Html.DropDownListFor(m => m.ProcessType, new[]{
new SelectListItem { Text = "Processed", Value = "Processed" },
new SelectListItem { Text = "Both", Value = "Both" }
}, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.ProcessType, null, new { #class = "alert-danger" })
</div>
<div class="form-group">
<button type="submit" class="btn btn-lg btn-primary">Save</button>
#Html.ActionLink("Cancel", "Manager", "Administration", null, new { #class = "btn btn-lg btn-default" })
</div>
}
</div>
</div>
#{
string password = "";
var entity = new NV.Tax.SST.Gateway.DB.Entities.sstpEntities();
var data = from db in entity.users
where db.username == name
select db;
foreach(var item in data)
{
password = item.password;
<script>document.getElementById("Password").defaultValue = "#password"</script>
if (item.processtype == "B")
{
<script>document.getElementById("ProcessType").value = "Both"</script>
}
else
{
<script>document.getElementById("ProcessType").value = "Processed"</script>
}
}
}
You should also add [HttpPost] attribute and change your controller action method as below
[HttpPost]
public ActionResult EditUserSubmit(NV.Tax.SST.Gateway.MVC.Models.AdministrationModel model)
{
string process = (model.ProcessType == "Processed") ? "P" : "B";
DB.Entities.user users = db.users.Where(m => m.username == model.UserName).FirstOrDefault();
users.password = model.Password;
users.processtype = process;
db.SaveChanges();
return RedirectToAction("Manager");
}
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.