I would appreciate some help here. I am trying to create a ASP.NET web app using MVC 5 EF. I have scaffolded my model to generate views and controller and apparently the create button/ insert button doesn't respond (doesn't insert values into the db but i can insert values directly on the db interface). I am suspecting its something to do with the GUID value that i use as a primary key.
Here are my codes
model
public class Supplier
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid SupplierId { get; set; }
[Required]
[Display(Name = "Supplier Name")]
[StringLength(100, ErrorMessage = "Name cannot be longer than 30 characters.")]
[Remote("doesSupplierExist", "Supplier", HttpMethod = "POST", ErrorMessage = "Duplicate Supplier Name Detected")]
public string Name { get; set; }
[Required]
[Display(Name = "Supplier phone Number")]
public int Phone { get; set; }
[Required]
[Display(Name = "Supplier Email")]
[StringLength(100, ErrorMessage = "Email cannot be longer than 50 characters.")]
public string Email { get; set; }
[Required]
[Display(Name = "Supplier Location")]
[StringLength(100, ErrorMessage = "Location cannot be longer than 50 characters.")]
public string Location { get; set; }
}
controller
public class SuppliersController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Suppliers
public async Task<ActionResult> Index()
{
return View(await db.Suppliers.ToListAsync());
}
// GET: Suppliers/Details/5
public async Task<ActionResult> Details(Guid? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Supplier supplier = await db.Suppliers.FindAsync(id);
if (supplier == null)
{
return HttpNotFound();
}
return View(supplier);
}
// GET: Suppliers/Create
public ActionResult Create()
{
return View();
}
// POST: Suppliers/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include ="SupplierId,Name,Phone,Email,Location")] Supplier supplier)
{
if (ModelState.IsValid)
{
supplier.SupplierId = Guid.NewGuid();
db.Suppliers.Add(supplier);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View("Index");
}
// GET: Suppliers/Edit/5
public async Task<ActionResult> Edit(Guid? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Supplier supplier = await db.Suppliers.FindAsync(id);
if (supplier == null)
{
return HttpNotFound();
}
return View(supplier);
}
// POST: Suppliers/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "SupplierId,Name,Phone,Email,Location")] Supplier supplier)
{
if (ModelState.IsValid)
{
db.Entry(supplier).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(supplier);
}
// GET: Suppliers/Delete/5
public async Task<ActionResult> Delete(Guid? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Supplier supplier = await db.Suppliers.FindAsync(id);
if (supplier == null)
{
return HttpNotFound();
}
return View(supplier);
}
// POST: Suppliers/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(Guid id)
{
Supplier supplier = await db.Suppliers.FindAsync(id);
db.Suppliers.Remove(supplier);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
Create View
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_dashboardLayout.cshtml";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Supplier</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Phone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Phone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Location, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Location, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Location, "", 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>
Migration
CreateTable("dbo.Suppliers",
c => new
{
SupplierId = c.Guid(nullable: false, identity: true,
defaultValueSql: "newsequentialid()"),
Name = c.String(nullable: false, maxLength: 100),
Phone = c.Int(nullable: false),
Email = c.String(nullable: false, maxLength: 100),
Location = c.String(nullable: false, maxLength: 100),
})
.PrimaryKey(t => t.SupplierId);
You need to remove the following attribute from your primary key.
DatabaseGenerated(DatabaseGeneratedOption.Identity)
You're providing a value, you don't need the database to generate one for you. Besides, to the best of my knowledge you can't have a GUID (uniqueidentifier in SQL) as an Identity column.
Related
when i tried to submit my edit form i get this issue and i don't know why
productsController edit get
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//ProductsModel productsModel = await db.ProductsModels.FindAsync(id);
var products = await db.ProductsModels.Include(a =>a.categorieId).Include(a => a.users).FirstAsync(a => a.id == id);
if (products == null)
{
return HttpNotFound();
}
var selectedOwnerId = products.users?.Id ?? string.Empty;
var users = db.Users.Select(userItem => new SelectListItem
{
Text = userItem.Email,
Value = userItem.Id,
Selected = userItem.Id == selectedOwnerId
}).ToSafeReadOnlyCollection();
var selectedCategoryId = products.categorieId.id;
var productCategories = db.ProductCategoriesModels
.Select(a => new SelectListItem
{
Value = a.id.ToString(),
Text = a.name,
Selected = a.id == selectedCategoryId
}).ToSafeReadOnlyCollection();
var viewmodel = new productCreatEditViewModel()
{
Products = products,
productCategories = productCategories,
users = users
};
//ViewBag.users = userList;
//ViewBag.productcategorieId = new SelectList(db.ProductCategoriesModels, "id", "Name", productsModel.productcategorieId);
return View(viewmodel);
}
productsController edit post
// POST: Products/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "id,name,calorie,price,productcategorieId,userId")] ProductsModel productsModel)
{
if (ModelState.IsValid)
{
db.Entry(productsModel).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.productcategorieId = new SelectList(db.ProductCategoriesModels, "id", "Name", productsModel.productcategorieId);
return View(productsModel);
}
edit view
#model koelkast.ViewModels.productCreatEditViewModel
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ProductsModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Products.id)
<div class="form-group">
#Html.LabelFor(model => model.Products.name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Products.name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Products.name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Products.calorie, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Products.calorie, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Products.calorie, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Products.price, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Products.price, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Products.price, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Products.categorieId.name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => Model.Products.categorieId.id,Model.productCategories, new { Name = "productCategoriesId", #class ="form-control"})
#Html.ValidationMessageFor(model => model.productCategories, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Products.users.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => Model.Products.users.Id,Model.users, new {Name = "UserId", #class = "form-control" })
#Html.ValidationMessageFor(model => model.Products.users.Email, "", 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>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
ViewModel
The model item passed into the dictionary is of type 'koelkast.Models.ProductsModel', but this dictionary requires a model item of type 'koelkast.ViewModels.productCreatEditViewModel'.
namespace koelkast.ViewModels
{
public class productCreatEditViewModel
{
[Required]
public ProductsModel Products { get; set; }
[Required]
public ICollection<SelectListItem> productCategories { get; set; }
[Required]
public ICollection<SelectListItem> users { get; set; }
}
}
productModel
namespace koelkast.Models
{
public class ProductsModel
{
[Key]
public int id { get; set; }
[Required,Display(Name = "name")]
public string name { get; set; }
//display name is de naam die hij gaat laten zien als nnaam in je view
[Required, Display(Name = "calorie")]
public int calorie { get; set; }
[Required, Display(Name = "price")]
public float price { get; set; }
[Display(Name = "categories")]
//hier zet je die foreing key
//zoals je kunt zien roep ik alleen de model aan
public int? productcategorieId { get; set; }
[ForeignKey("productcategorieId")]
public virtual ProductCategoriesModel categorieId { get; set; }
//je zegt hier dus dat dit de Id is(userId)
//van applicationUser table users
public string UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser users { get; set; }
}
}
https://i.stack.imgur.com/Qaq67.png
you have a bug here, fix it
public async Task<ActionResult> Edit(ProductsModel productsModel)
{
}
you have 2 choices
1.Change ProductsModel to ProductCreatEditViewModel
or
Return ProductCreatEditViewModel as model
var viewmodel = new productCreatEditViewModel()
{
Products = productsModel,
productCategories = productCategories,
users = users
};
return View(viewModel);
So I have some custom validation implemented to prevent similar records being entered into the db. The only problem I have is that it is not presenting the user an error/validation message but rather an error page.
Where am I going wrong? Or how do I correctly implement this?
Validation:
public class ValidSimilarRequests : ValidationAttribute
{
private LotusWorksEntities db = new LotusWorksEntities();
protected override ValidationResult
IsValid(object value, ValidationContext validationContext)
{
var model = (Models.HolidayRequestForm)validationContext.ObjectInstance;
int empID = Convert.ToInt32(model.EmployeeID);
DateTime _startdate = Convert.ToDateTime(model.StartDate);
DateTime _finishdate = Convert.ToDateTime(model.FinishDate);
var holidayexist = db.HolidayRequestForms.Any( x => x.EmployeeID==empID && x.StartDate <= _startdate && x.FinishDate >= _finishdate );
if (holidayexist)
{
return new ValidationResult
("A holiday Request for this date range has already been requested");
}
else
{
return ValidationResult.Success;
}
}
}
Model:
public partial class HolidayRequestForm
{
public int RequestID { get; set; }
[ValidSimilarRequests(ErrorMessage =
"A holiday Request for this date range has already been requested")]
public int EmployeeID { get; set; }
[ValidSameWeek(ErrorMessage =
"Holiday Request Must be made on a weekly Period")]
[DisplayFormat(DataFormatString = "{0:dd/MMM/yy}", ApplyFormatInEditMode = true)]
public System.DateTime StartDate { get; set; }
[ValidStartFinishDate(ErrorMessage =
"Finish Date can not be Greater than Start date.")]
[DisplayFormat(DataFormatString = "{0:dd/MMM/yy}", ApplyFormatInEditMode = true)]
public System.DateTime FinishDate { get; set; }
[Range(0.0001, int.MaxValue, ErrorMessage = "Hours Requested must be greater than zero. ")]
public decimal HoursTaken { get; set; }
public string Comments { get; set; }
public int YearCreated { get; set; }
public int MonthCreated { get; set; }
public int DayCreated { get; set; }
public Nullable<int> YearOfHoliday { get; set; }
public Nullable<bool> Approved { get; set; }
public string SubmittedBy { get; set; }
public string ApprovedBy { get; set; }
public Nullable<int> WorkWeek { get; set; }
public Nullable<int> MonthOfHoliday { get; set; }
public virtual Employee Employee { get; set; }
}
The Error Page shows:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
Controller:
[Authorize(Roles = "Admin,User,SuperUser")]
public ActionResult Create()
{
ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "FullName");
return View();
string name = Session["Name"].ToString();
var EmployeeIDCatch = db.Employees.Where(s => s.Email.Equals(name)).Select(s => s.EmployeeID);
}
// POST: HolidayRequestForms/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "RequestID,StartDate,FinishDate,HoursTaken,Comments,YearCreated,MonthCreated,DayCreated,YearOfHoliday,Approved,SubmittedBy,ApprovedBy")] HolidayRequestForm holidayRequestForm)
{
if (ModelState.IsValid)
{
if (Session["Name"] == null)
{
TempData["msg"] = "Your Session Expired - Please Login";
return RedirectToAction("Login", "Account");
}
string name = Session["Name"].ToString();
var employeeID = db.Employees.Where(s => s.Email.Equals(name)).Select(s => s.EmployeeID).FirstOrDefault();
holidayRequestForm.EmployeeID = employeeID;
var submittedby = db.Employees.Where(s => s.Email.Equals(name)).Select(s => s.Email).FirstOrDefault();
holidayRequestForm.SubmittedBy = submittedby;
//Saves changes and begins Email Actions
db.HolidayRequestForms.Add(holidayRequestForm);
db.SaveChanges();
SendMailToAreaManager();
SendMailToManager();
SendMailToAdmin();
return RedirectToAction("Index", "Calendar");
}
ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "FullName", holidayRequestForm.EmployeeID);
return View(holidayRequestForm);
}
VIEW:
#model HolidayTracker.Models.HolidayRequestForm
<div>
<div class="col-md-12">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<h2 align="center">Holiday Request Form</h2>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.StartDate, "Start Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StartDate, "Start Date", new { htmlAttributes = new { #class = "form-control", #style = "width:400px", autocomplete = "off" } })
#Html.ValidationMessageFor(model => model.StartDate, "", new { #class = "text-warning" })
<p id="warning" style="color:orange"></p>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FinishDate, "Finish Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FinishDate, new { htmlAttributes = new { #class = "form-control",#style = "width:400px", autocomplete = "off" } })
#Html.ValidationMessageFor(model => model.FinishDate, "", new { #class = "text-danger" })
<p id="warningFD" style="color:orange"></p>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.HoursTaken, "Hours Requested", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HoursTaken, new { htmlAttributes = new { #class = "form-control", #style = "width:400px" } })
#Html.ValidationMessageFor(model => model.HoursTaken, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Comments, htmlAttributes: new { #class = "control-label col-md-2"})
<div class="col-md-10">
#Html.TextAreaFor(
model => model.Comments,
new { placeholder = "Enter Dates and how many Hours per Date Here. ", style = "width: 400px; height: 200px;" })
#Html.ValidationMessageFor(model => model.Comments, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Submit" class="btn btn-warning" />
</div>
</div>
}
</div>
</div>
</div>
I'm creating a web app, and I can't seem to either create or edit entries with a foreign key. I'm creating a dropdown list to edit the records, and it's being populated correctly. But anytime I edit or create a new record with that foreign key I get "The value '2' is invalid."
My Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "chimeTimeID,ScheduleID,ChimeTimeStamp")] ChimeTime chimeTime)
{
ViewData["scheduleID"] = new SelectList(db.Schedules, "scheduleID", "ScheduleName", "Select a Schedule");
ViewBag.defaultModem = new SelectList(db.Schedules, "scheduleID", "ScheduleName", "Select a Schedule");
if (ModelState.IsValid)
{
db.Entry(chimeTime).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(chimeTime);
}
My View
<div class="form-group">
#Html.LabelFor(model => model.ScheduleID.ScheduleName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="dropdown">
#Html.DropDownListFor(model => model.ScheduleID, (SelectList)ViewBag.ScheduleName, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ScheduleID, "", new { #class = "text-danger" })
</div>
</div>
My Model
[Table("P_ChimeTime")]
public class ChimeTime
{
[Key]
public int chimeTimeID { get; set; }
public Schedule ScheduleID { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:T}", ApplyFormatInEditMode = true)]
public DateTime ChimeTimeStamp { get; set; }
}
So what am I doing wrong? It appears to me that MVC isn't parsing my result from the form to an int like it should.
So apparently this is how it should have been:
My Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "chimeTimeID,schedule,ChimeTimeStamp")] ChimeTime chimeTime)
{
ViewData["schedule"] = new SelectList(db.Schedules, "scheduleID", "ScheduleName", "Select a Schedule");
ViewBag.schedule = new SelectList(db.Schedules, "scheduleID", "ScheduleName", "Select a Schedule");
if (ModelState.IsValid)
{
chimeTime.ScheduleID = db.Schedules.Find (Int32.Parse (Request ["schedule"]));
db.ChimeTimes.Add(chimeTime);
db.SaveChanges();
return RedirectToAction("Index");
}
buildChimeJob(chimeTime);
return View(chimeTime);
}
My View:
<div class="form-group">
#Html.LabelFor(model => model.schedule, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="dropdown">
#Html.DropDownListFor(model => model.schedule, (SelectList)ViewBag.schedule, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.schedule, "", new { #class = "text-danger" })
</div>
</div>
My Model:
[Table("P_ChimeTime")]
public class ChimeTime
{
[Key]
public int chimeTimeID { get; set; }
public virtual Schedule ScheduleID { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:T}", ApplyFormatInEditMode = true)]
public DateTime ChimeTimeStamp { get; set; }
[ForiegnKey("ScheduleID")]
public int schedule {get; set;}
}
Following is my code and I don't know why my validator is not working
First code is User model then second is home controller and last is view of the Index action result.I am new to MVC.COuld you please help me.
Thanks
public class User
{
[Required(ErrorMessage = "UserName is required")]
public string UserName { get; set; }
[Required(ErrorMessage = "Password is required")]
public string Pasword { get; set; }
}
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string uname,string pass)
{
if(ModelState.IsValid)
{
User user = new User();
user.UserName = uname;
user.Pasword = pass;
string Username = ConfigurationManager.AppSettings["username"].ToString();
string passwrd = ConfigurationManager.AppSettings["password"].ToString();
if (user.UserName !=null && user.Pasword !=null)
{
if(user.UserName==Username && user.Pasword==passwrd)
{
return RedirectToAction("Detail", "Home");
}
}
}
return View("Index");
}
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.UserName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Pasword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Pasword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Pasword, "", new { #class = "text-danger" })
</div>
</div>
first of all you should send model instead of individual properties like
[HttpPost]
public ActionResult Index(User user)
{
if(!ModelState.IsValid)
{
return View("Index",user);
}
// your code here if model is valid
return View("Index");
}
it will check if ModelState is Invalid it will redirect to the same view with ModelState which will include key and value so if validation of a property fails its name will be the key and message will be in the value of the key validation messages will be populated according to their keys(property names)
Got 3 tables :
Question (QuestionId,QuestionText)
Survey(SurveyId,QuestionId,UserId,AnswerTExt,Comment)
User(UserId,UserName)
How to make a form in a view for all questions in table question .
Example I got 90 questions , when I answer this form 5 times , Table answers must have 450 records
Controller:
public class SurveysController : Controller
{
private TESTEntities db = new TESTEntities();
// GET: Surveys
public ActionResult Index()
{
var surveys = db.Surveys.Include(s => s.Question).Include(s => s.User);
return View(surveys.ToList());
}
// GET: Surveys/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Survey survey = db.Surveys.Find(id);
if (survey == null)
{
return HttpNotFound();
}
return View(survey);
}
// GET: Surveys/Create
public ActionResult Create()
{
ViewBag.QuestionId = new SelectList(db.Questions, "QuesionId", "QuestionText");
ViewBag.UserId = new SelectList(db.Users, "UserId", "Name");
return View();
}
// POST: Surveys/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "SuerveyId,UserId,QuestionId,Answer,Comment")] Survey survey)
{
if (ModelState.IsValid)
{
db.Surveys.Add(survey);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.QuestionId = new SelectList(db.Questions, "QuesionId", "QuestionText", survey.QuestionId);
ViewBag.UserId = new SelectList(db.Users, "UserId", "Name", survey.UserId);
return View(survey);
}
// GET: Surveys/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Survey survey = db.Surveys.Find(id);
if (survey == null)
{
return HttpNotFound();
}
ViewBag.QuestionId = new SelectList(db.Questions, "QuesionId", "QuestionText", survey.QuestionId);
ViewBag.UserId = new SelectList(db.Users, "UserId", "Name", survey.UserId);
return View(survey);
}
// POST: Surveys/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "SuerveyId,UserId,QuestionId,Answer,Comment")] Survey survey)
{
if (ModelState.IsValid)
{
db.Entry(survey).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.QuestionId = new SelectList(db.Questions, "QuesionId", "QuestionText", survey.QuestionId);
ViewBag.UserId = new SelectList(db.Users, "UserId", "Name", survey.UserId);
return View(survey);
}
// GET: Surveys/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Survey survey = db.Surveys.Find(id);
if (survey == null)
{
return HttpNotFound();
}
return View(survey);
}
// POST: Surveys/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Survey survey = db.Surveys.Find(id);
db.Surveys.Remove(survey);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
Create View:
#model TEST.Models.Survey
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Survey</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.UserId, "UserId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("UserId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.UserId, "", new { #class = "text-danger" })
</div>
</div>
#foreach (var item in ViewBag.QuestionId)
{
<div class="form-group">
#Html.LabelFor(model => model.QuestionId, "QuestionId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.HiddenFor(s=>s.QuestionId)
#Html.ValueFor(s =>item)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Answer, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Answer, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Answer, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Comment, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Comment, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Comment, "", 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>
First I want to make sure I understand what you are trying to do.
In your Create action you are getting all the Questions from the Question table and adding them to the View bag as QuestionId.
Assuming that when you debug the code, you see the correct data in Viewbag.QuestionId when you try to print your label to the screen with
#Html.LabelFor(model => model.QuestionId, "QuestionId", htmlAttributes: new { #class = "control-label col-md-2" })
You are trying to print out the object of QuestionId. I think you need to use 'item' in your label because this changes as your code iterates through the collection.
item.Question
should be used where you want to print out the text of the question