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
Related
I have created a model with a controller and a view in my ASP.NET MVC application. Initially, when a new application is created using the create action, the user doesn't have the possibility to fill in 5 of the parts of the model (see code).
Editing is only possible when logging in as an admin, not as any user. Getting the edit page for the right application connected to the right user is not a problem. HOWEVER, when I fill in the checkboxes and write any comments etc. in the 'edit mode', and press submit, nothing happens. It seems the changes are not registered by the program (db.SaveChanges() doesn't work??)
Please, do someone know how I can fix this, or to begin with, what the problem is? It is almost as if the save button is just a shell, so might there me a connection or something missing?
Thank you for your time.
code:
part of the model (last 5 are not filled in in 'create mode'
[Display(Name = "Course for master")]
public string Course_Master { get; set; }
[Required]
[Display(Name = "Words for Office")]
[MaxLength(3000)]
public string Motivation { get; set; }
//[DataType(DataType.Upload)]
[Display(Name = "Upload Resume")]
//[Required(ErrorMessage = "Please choose file to upload")]
public string Resume { get; set; }
//these 5 are the ones I want to edit
public bool Interview { get; set; } //checkbox
public string Comments { get; set; }
public string Notes { get; set; }
public bool Unfit { get; set; } //checkbox
public bool Candidate { get; set; } //checkbox
razor page
#model NEA.Models.Application
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
#using (Html.BeginForm("Edit","Applications", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Application</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.UserId)
<div class="form-group">
#Html.LabelFor(model => model.Interview, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Interview)
#Html.ValidationMessageFor(model => model.Interview, "", new { #class = "text-danger" })
</div>
</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.EditorFor(model => model.Comments, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Comments, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Notes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Notes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Notes, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Unfit, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Unfit)
#Html.ValidationMessageFor(model => model.Unfit, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Candidate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Candidate)
#Html.ValidationMessageFor(model => model.Candidate, "", new { #class = "text-danger" })
</div>
</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>
action
// GET: Applications/Edit/5
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Application application = db.Applications.Find(id);
if (application == null)
{
return HttpNotFound();
}
return View(application);
}
// POST: Applications/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Application application)
{
if (ModelState.IsValid)
{
db.Entry(application).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(application);
}
Edit
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Application application)
{
//db.Entry(application).State = EntityState.Modified;
db.Entry(application).Property(o => o.Interview).IsModified = true;
db.Entry(application).Property(o => o.Comments).IsModified = true;
db.Entry(application).Property(o => o.Notes).IsModified = true;
db.Entry(application).Property(o => o.Unfit).IsModified = true;
db.Entry(application).Property(o => o.Candidate).IsModified = true;
db.SaveChanges();
return RedirectToAction("Index");
//return View(application);
}
If you want to change certain values, according to your above code does not know which property is modified. You can set properties as isModified=true that you want to change value of properties.
EDIT:
db.Application.Attach(application);
db.Entry(application).Property(o => o.Interview).IsModified = true;
db.Entry(application).Property(o => o.Comments).IsModified = true;
db.SaveChanges();
return RedirectToAction("Index");
Or you can make this below way with list;
var included= new[] { "Interview ", "Comments " };
var entry = context.Entry(obj);
entry.State = EntityState.Modified;
foreach (var name in included)
{
entry.Property(name).IsModified = true;
}
I figured out how to fix it, whilst keeping #Html.BeginForm() empty
edit action
// POST: Applications/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Application application, string id)
{
var data = db.Applications.Find(id);
data.Interview = application.Interview;
data.Comments = application.Comments;
data.Notes = application.Notes;
data.Unfit = application.Unfit;
data.Candidate = application.Candidate;
db.SaveChanges();
return RedirectToAction("Index");
}
This question already has answers here:
Populating a razor dropdownlist from a List<object> in MVC
(9 answers)
Closed 3 years ago.
I have a view to create an 'Appointment' after choosing some options in 3 different drop-down menus (Patient, Doctor, Clinic)
I need help with creating and populating these 3 drop-down menus.
I'm pretty new to ASP.NET MVC and C#. So, your help is most appreciated.
I'll include the appointment controller and appointment creation view code.
AppointmentController
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ClinicManagement.Models;
namespace ClinicManagement.Controllers
{
public class AppointmentController : Controller
{
// GET: Appointment
public ActionResult Index()
{
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
return View(DataBase.Appointments.ToList());
}
}
// GET: Appointment/Details/5
public ActionResult Details(int id)
{
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
return View(DataBase.Appointments.Where(x => x.AppintID == id).FirstOrDefault());
}
}
// GET: Appointment/Create
public ActionResult Create()
{
return View();
}
// POST: Appointment/Create
[HttpPost]
public ActionResult Create(Appointment appointment)
{
try
{
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
DataBase.Appointments.Add(appointment);
DataBase.SaveChanges();
}
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Appointment/Edit/5
public ActionResult Edit(int id)
{
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
return View(DataBase.Appointments.Where(x => x.AppintID == id).FirstOrDefault());
}
}
// POST: Appointment/Edit/5
[HttpPost]
public ActionResult Edit(int id, Appointment appointment)
{
try
{
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
DataBase.Entry(appointment).State = EntityState.Modified;
DataBase.SaveChanges();
}
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Appointment/Delete/5
public ActionResult Delete(int id)
{
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
return View(DataBase.Appointments.Where(x => x.AppintID == id).FirstOrDefault());
}
}
// POST: Appointment/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
using (HospitalDatabaseEntities DataBase = new HospitalDatabaseEntities())
{
Appointment appointment = (DataBase.Appointments.Where(x => x.AppintID == id).FirstOrDefault());
DataBase.Appointments.Remove(appointment);
DataBase.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Appointment 'Create' View
#model ClinicManagement.Models.Appointment
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Appointment</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.DoctorID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DoctorID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DoctorID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PatientID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PatientID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PatientID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ClinicID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ClinicID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ClinicID, "", 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 Appointment" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
If the drop down menu options are in a database, why not add a list to your model, populate that list in your GET ActionMethod and then render it using the DropdownListFor helper tag.
For example...
public class Appointment
{
public IEnumerable<SelectListItem> Clinic {get; set;}
//You should add this for every dropdown menu you intend to put in the list.
//I am guessing you already have a model like this as this was not in the question
}
public class Clinic
{
public int ClinicId {get; set;}
public string ClinicName {get; set;}
}
In the controller, you can then query the database for the options
public ActionResult Create()
{
var Clinic = context.Clinic.ToList();
var model = new Appointments()
{
Clinic = Clinic.Select(x => new SelectListItem
{
Value = x.ClinicId.ToString(),
Text = x.ClinicName
}
}
return View(model);
}
Like before, you would have to do this for all the fields. If you are worried about the numerous roundtrip to the database to get the values, do some research about Z.EntityFrameWork nuget pakages that lets you run batch SQL statements so you can get all three results with one database round trip.
Then in the view, you can do this...
#Html.DropDownListFor(m => m.ClinicId, Model.Clinic, "Select Clinic", new { #class = "form-control", id = "clinic" })
In Create controller GET , you should create 3 viewbag like
ViewBag.Patient = Database.Patient.ToList();
...
and in view, use dropdownlist:
#Html.DropDownList("PatientId", new SelectList(ViewBag.Accounts, "PatientId", "PatientName")), "choose the patient", new { #class = "form-control" }))
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.
The error message I get:
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Member/EditMember
My Actionlink that calls the Edit method looks like this:
#Html.ActionLink("Rediger", "EditMember", new { item.MemberID })
And the view that represents the EditMember page:
#using (Html.BeginForm("EditMember", "Member", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.MemberID)
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "Navn skal angives", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div
...
}
And the controller action:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditMember(Member model)
{
Member members = new Member();
var member = DBContext.Members.Find(model.MemberID);
if (member == null)
{
return HttpNotFound();
}
if(ModelState.IsValid)
{
DBContext.SaveChanges();
}
return View(member);
}
I have also tried to change the action methods parameter so it looks like this
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditMember(int? id) { ... }
But the error remains the same.
HOWEVER...
If I remove the [HttpPost annotation, then the error dissappears, and it will find the requested URL. But it just won't submit the changes and save them to the database.
That is, if I do:
[ValidateAntiForgeryToken]
public ActionResult EditMember(Member model)
Then it finds the requested URL, but doesn't save the changes to the database.
What might be my problem?
I suspect you are not passing the Id in the HttpGet method. This could be as a result of using a ViewModel to display member info.
There is no row in the table with the specified member Id.
In your controller you should have two actions (HttpGet and HttpPost)
[HttpGet]
public ActionResult EditMember(int id)
{
var member = db.member..SingleOrDefault(x => x.Id == id);
if (member != null)
{
var memberViewModel = new MemberViewModel();
memberViewModel.MemberID = member.Id;
memberViewModel.FirstName = member.FirstName;
memberViewModel.LastName = member.LastName;
return View(memberViewModel);
}
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditMember(Member model)
{
Member members = new Member();
var member = DBContext.Members.Find(model.MemberID);
if (member == null)
{
return HttpNotFound();
}
if(ModelState.IsValid)
{
DBContext.SaveChanges();
}
return View(member);
}
Please don't argue me too hard, I'm just a beginner in asp.net
I have made controllers/views based on this model http://tinypic.com/view.php?pic=awq14w&s=8#.VG2Q4PmUdUV
When I create a new Survey I have this view http://tinypic.com/view.php?pic=33ayubs&s=8#.VG2R6fmUdUV
How can I modify the view in order to get this form type when I create/view/edit:
Questions | Answers | Comments
------------------------------
Q1 | TextBox | TextBox
Q2 | TextBox | TextBox
Q3 | TextBox | TextBox
Controller :
public class SurveysController : Controller
{
private OrganizationASEMEntities1 db = new OrganizationASEMEntities1();
// 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, "QuestionId", "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 = "SurveyId,UserId,QuestionId,Answer,Comment")] Survey survey)
{
if (ModelState.IsValid)
{
db.Surveys.Add(survey);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.QuestionId = new SelectList(db.Questions, "QuestionId", "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, "QuestionId", "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 = "SurveyId,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, "QuestionId", "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);
}
}
}
View Create:
#model OrganizationASEM.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>
<div class="form-group">
#Html.LabelFor(model => model.QuestionId, "QuestionId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("QuestionId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.QuestionId, "", new { #class = "text-danger" })
</div>
</div>
enter code here
<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>
View Edit:
#model OrganizationASEM.Models.Survey
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Survey</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.SurveyId)
<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>
<div class="form-group">
#Html.LabelFor(model => model.QuestionId, "QuestionId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("QuestionId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.QuestionId, "", new { #class = "text-danger" })
</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="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
View Index:
#model IEnumerable<OrganizationASEM.Models.Survey>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Answer)
</th>
<th>
#Html.DisplayNameFor(model => model.Comment)
</th>
<th>
#Html.DisplayNameFor(model => model.Question.QuestionText)
</th>
<th>
#Html.DisplayNameFor(model => model.User.Name)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Answer)
</td>
<td>
#Html.DisplayFor(modelItem => item.Comment)
</td>
<td>
#Html.DisplayFor(modelItem => item.Question.QuestionText)
</td>
<td>
#Html.DisplayFor(modelItem => item.User.Name)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.SurveyId }) |
#Html.ActionLink("Details", "Details", new { id=item.SurveyId }) |
#Html.ActionLink("Delete", "Delete", new { id=item.SurveyId })
</td>
</tr>
}
</table>
If you want to have all fieds in a single row you have to switch from:
<div class="form-horizontal">
to:
<div class="form-inline">
see here:
http://getbootstrap.com/css/#forms