I'm trying to get a range slider input on my c# mvc 5 view page that i can submit the input to the mvc controller to write to a database. i tried using Jquery Ui Slider but i couldn't figure how to get the values over to my c# code for writing form data to database.
here's the view cshtml file
#model RateMyCourse.ReviewCourse
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ReviewCourse</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Review, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Review, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Review, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Relevance, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Relevance, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Relevance, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Fun, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Fun, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Fun, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Difficulty, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Difficulty, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Difficulty, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Clarity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Clarity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Clarity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Rating, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Rating, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Rating, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Like, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Like, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Like, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Dislike, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Dislike, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Dislike, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CourseCourseId, "CourseCourseId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CourseCourseId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CourseCourseId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.User_UserId, "User_UserId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("User_UserId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.User_UserId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
and here's the Controller file
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using RateMyCourse;
namespace RateMyCourse.Controllers
{
public class ReviewCoursesController : Controller
{
private CollegeRocksEntities db = new CollegeRocksEntities();
// GET: ReviewCourses
public ActionResult Index()
{
var reviewCourse = db.ReviewCourse.Include(r => r.Course).Include(r => r.User);
return View(reviewCourse.ToList());
}
// GET: ReviewCourses/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ReviewCourse reviewCourse = db.ReviewCourse.Find(id);
if (reviewCourse == null)
{
return HttpNotFound();
}
return View(reviewCourse);
}
// GET: ReviewCourses/Create
public ActionResult Create()
{
ViewBag.CourseCourseId = new SelectList(db.Course, "CourseId", "Name");
ViewBag.User_UserId = new SelectList(db.User, "UserId", "UserName");
return View();
}
// POST: ReviewCourses/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 = "ReviewCourseId,Review,Relevance,Fun,Difficulty,Clarity,Rating,Like,Dislike,CourseCourseId,User_UserId")] ReviewCourse reviewCourse)
{
if (ModelState.IsValid)
{
db.ReviewCourse.Add(reviewCourse);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CourseCourseId = new SelectList(db.Course, "CourseId", "Name", reviewCourse.CourseCourseId);
ViewBag.User_UserId = new SelectList(db.User, "UserId", "UserName", reviewCourse.User_UserId);
return View(reviewCourse);
}
// GET: ReviewCourses/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ReviewCourse reviewCourse = db.ReviewCourse.Find(id);
if (reviewCourse == null)
{
return HttpNotFound();
}
ViewBag.CourseCourseId = new SelectList(db.Course, "CourseId", "Name", reviewCourse.CourseCourseId);
ViewBag.User_UserId = new SelectList(db.User, "UserId", "UserName", reviewCourse.User_UserId);
return View(reviewCourse);
}
// POST: ReviewCourses/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 = "ReviewCourseId,Review,Relevance,Fun,Difficulty,Clarity,Rating,Like,Dislike,CourseCourseId,User_UserId")] ReviewCourse reviewCourse)
{
if (ModelState.IsValid)
{
db.Entry(reviewCourse).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CourseCourseId = new SelectList(db.Course, "CourseId", "Name", reviewCourse.CourseCourseId);
ViewBag.User_UserId = new SelectList(db.User, "UserId", "UserName", reviewCourse.User_UserId);
return View(reviewCourse);
}
// GET: ReviewCourses/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ReviewCourse reviewCourse = db.ReviewCourse.Find(id);
if (reviewCourse == null)
{
return HttpNotFound();
}
return View(reviewCourse);
}
// POST: ReviewCourses/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
ReviewCourse reviewCourse = db.ReviewCourse.Find(id);
db.ReviewCourse.Remove(reviewCourse);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Most likely you have missed one of these:
a) does my element in view has corresponding name
<input type="number" class="nmbr" name="second"/>
b) have I included my wanted element in bindings list
public ActionResult Create([Bind(Include = "second")] ReviewCourse reviewCourse)
these 2 are most likely reasons. And if still it is missing, check if you are actually posting all the data.
Related
I am making a web application and I used entity based EF designer from database model I want to hide modified by and modified Date for the backend and it shouldn't display to the user Can someone help how do I make this work? I have attached my picture and code below please let me know if there is any question.
Picture:
Controller CODE:
// GET: Contract
public ActionResult Index()
{
return View(db.Contracts.ToList());
}
// GET: Contract/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Contract contract = db.Contracts.Find(id);
if (contract == null)
{
return HttpNotFound();
}
return View(contract);
}
// GET: Contract/Create
public ActionResult Create()
{
return View();
}
// POST: Contract/Create
// 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 ActionResult Create(\[Bind(Include = "Id,ContractName,ContractNumber,CreatedBy,CreatedDate,ModifiedBy,ModifiedDate")\] Contract contract)
{
if (ModelState.IsValid)
{
db.Contracts.Add(contract);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(contract);
}
// GET: Contract/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Contract contract = db.Contracts.Find(id);
if (contract == null)
{
return HttpNotFound();
}
return View(contract);
}
// POST: Contract/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 ActionResult Edit(\[Bind(Include = "Id,ContractName,ContractNumber,CreatedBy,CreatedDate,ModifiedBy,ModifiedDate")\] Contract contract)
{
if (ModelState.IsValid)
{
db.Entry(contract).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(contract);
}
// GET: Contract/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Contract contract = db.Contracts.Find(id);
if (contract == null)
{
return HttpNotFound();
}
return View(contract);
}
// POST: Contract/Delete/5
\[HttpPost, ActionName("Delete")\]
\[ValidateAntiForgeryToken\]
public ActionResult DeleteConfirmed(int id)
{
Contract contract = db.Contracts.Find(id);
db.Contracts.Remove(contract);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
`
I tried to figure out but I don't know how to hide these two modified date and modified by at the backend.
View code
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Contract</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ContractName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ContractName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ContractName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContractNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ContractNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ContractNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreatedBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CreatedBy, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CreatedBy, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreatedDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CreatedDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CreatedDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ModifiedBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ModifiedBy, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ModifiedBy, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ModifiedDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ModifiedDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ModifiedDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button style="background-color:white; border-color:darkgrey;"><input type="submit" value="Create" class="btn btn-default" /></button>
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Often times the entity types stored in the database have fields you don't want to, can't, or shouldn't expose on the UI.
If you're not concerned about the data being present and would just like to "hide" it, simply don't include those in the table markup.
If however you don't want the fields present at all, a common way to get around that is to create a DTO class that only has the fields you wish to expose. Update your UI to target the DTO and remove the columns from the table.
public class ContractDto
{
// all the fields you want to expose
// Ctor
public ContractorDto(Contract contract) { ... }
// "From" pattern
public static ContractDto From(Contract contract)
=> new ContractDto { ... }
// An implicit operator can also be helpful
public static implicit operator ContractDto(Contract contract)
=> new ContractDto { ... }
}
If you need to update the fields you dropped after an update for example, load the entity type using the primary key and update it. This assumes you have some way to populate the current user.
var entity = db.Contracts.Find(contractDto.Id);
// update entity from dto as needed
entity.ModifiedBy = // populate the user from context or similar
entity.ModifiedDate = DateTime.Now;
I have a class like so:
public class saveModel
{
public int ID{ get; set; }
[DisplayName("Area")]
public string Area { get; set; }
public string AreaDescription { get; set; }
[DisplayName("Model")]
public string Model { get; set; }
[DisplayName("Description")]
}
and in my controller I have this:
[Authorize]
public ActionResult ModelEdit(int id)
{
saveModel model = webService.getModel(id);
return View(model);
}
[Authorize]
[HttpPost]
public ActionResult ModelEdit(saveModel model)
{
return View();
}
and in view I have this:
#model MyApp.Models.saveModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ModelID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ModelID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ModelID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Area, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Area, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Area, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AreaDescription, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AreaDescription, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AreaDescription, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Model, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Model, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Model, "", 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 problem I am having is when I press the save button, it goes to the correct method, but my saveModel is empty on submit...what am I doing wrong?
try including the from body attribute as below
[Authorize]
[HttpPost]
public ActionResult ModelEdit([FromBody]saveModel model)
{
return View();
}
if it doesn't solve your problem, then an invalid or an empty value is being passed to your ID field. You can check the ModelState property, which will point to the right field.
I m a student I m Learning MVC.
I have only one table for login and registration.
problem is login is not working as well as registration is not work
stanstuds.cs
public class stanstuds
{
[Key]
public int id { get; set; }
public string fname { get; set; }
public string mname { get; set; }
public string lname { get; set; }
public string country { get; set; }
public string usertype { get; set; }
public string username { get; set; }
public string password { get; set; }
}
context class
public class stanstudcontext:DbContext
{
public stanstudcontext():base("cnnos")
{
}
public DbSet<stanstuds> studs { get; set; }
}
controller
public class LogRegController : Controller
{
stanstudcontext context = new stanstudcontext();
//admin view just I print the sample message this is an admin view
public ActionResult Index()
{
return View();
}
//client view just I print the sample message this is a client view
public ActionResult Clientview()
{
return View();
}
//Login
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(stanstuds studs)
{
var userdata=context.studs.Where(x => x.username == studs.username && x.password == studs.password).FirstOrDefault();
if (userdata != null) //when i m debugging this condition is not check
{
// i have a 2 records of admin in database but when i run time enter that record login is not working
/// if (userdata.usertype == "admin")
//{
// return RedirectToAction("Index", "LogReg");
//}
//else
//{
// return RedirectToAction("Clientview", "LogReg");
//}
//}
/else
//{
// return View();
//}
if (userdata != null)
{
if (userdata.password == userdata.password) //success
{
//here give an error httpsessionstatebase does not contain a definition for setint32 and no extension method setnt32 are u missing directive or assembly reference???
HttpContext.Session.SetInt32("id", userdata.id);
if (userdata.usertype == "admin")
return RedirectToAction("Index", "LogReg");
else
return RedirectToAction("Clientview", "LogReg");
}
else
{
ViewBag.Message = "Invalid Password!";
return View();
}
}
else
{
ViewBag.Message = "Invalid Email!";
return View();
}
}
//Registration
public ActionResult Regis()
{
return View();
}
[HttpPost]
public ActionResult Regis(stanstuds studs)
{
context.studs.Add(studs);
context.SaveChanges();
return View();
}
}
Login.cshtml
#model LoginRegOneTable.Models.stanstuds
#{
ViewBag.Title = "Login";
}
<h2>Login</h2>
<html>
<head>
<title>Demo Website</title>
</head>
<body>
#using (Html.BeginForm())
{
<div>
<label>UserName:</label>
#Html.EditorFor(model => model.username)
</div>
<div>
<label>Password:</label>
#Html.EditorFor(model => model.password)
</div>
<div>
<input type="submit" value="Login" />
</div>
}
</body>
</html>
Regis.cshtml
#{
ViewBag.Title = "Regis";
}
<h2>Regis</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>stanstuds</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.fname, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.fname, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.fname, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.mname, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.mname, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.mname, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.lname, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.lname, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.lname, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.country, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.country, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.country, "", new { #class = "text-danger" })
</div>
</div>
**I think the problem is here I want to insert by default entry as a user but how???**
<div class="form-group">
#Html.LabelFor(model => model.usertype, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.usertype, new { htmlAttributes = new { #class = "form-control" ,#value = "User"} })
#Html.ValidationMessageFor(model => model.usertype, "", new { #class = "text-danger" })
</div>
</div>
<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.password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.password, "", 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>
when user registration then insert by default entry as a user my registration is not working when I press register button then the record is not inserted and when I press login then login is not working? something is wrong my script?? please help??
In this case, you can check if the typed password is equal to the password in database, and check if it works:
var userdata = context.studs.Where(x => x.username.Equals(studs.username)).FirstOrDefault();
if (userdata != null)
{
if (userdata.Password == userdata.Password) //success
{
HttpContext.Session.SetInt32("id", userdata.id);
if (userdata.usertype == "admin")
return RedirectToAction("Index", "LogReg");
else
return RedirectToAction("Clientview", "LogReg");
}
else
{
ViewBag.Message = "Invalid Password!";
return View();
}
}
else
{
ViewBag.Message = "Invalid Email!";
return View();
}
I'm trying to learn ASP.net MVC. I'm using the pre-populated asp.net project that has a fake website within it to start. I have a form, and on submit, I want to put the values into a table in my database. I would also like to add functionality that if the email already exists in the database, I redirect them to another page.
I've added my own view, model, and controller.
Here's my databases (Side question: should I just put the table I created into DefaultConnection instead of Users.mdf?)
My Model:
public class RegisterLoyaltyViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public string Password { get; set; }
public string Phone { get; set; }
public string SecurityQuestion { get; set; }
public string SecurityAnswer { get; set; }
public string optSweepstakes { get; set; }
public string optEmails { get; set; }
}
My relevant controller code:
// POST: /Account/RegisterLoyalty
[HttpPost]
[AllowAnonymous]
public void RegisterLoyalty(RegisterLoyaltyViewModel model)
{
//Currently nothing here
}
I think what I need to do is hit the database inside the controller. I need to check if email already exists in the table, and if it does, redirect to page x. If email does not exist, simply submit the model to the database, and redirect to page y.
You need a data layer implementation to hit the database, there are various ways of doing it one of which is using Entity Framework, have a look at here to get some ideas, or alternatively you can use ADO.NET to connect to the database.
Create a controller action to GET the RegisterLoyalty view. That view contains a the RegisterLoyalty form. Have the form POST to the RegisterLoyalty action. Then you can perform your logic and add the model to the db if necessary.
//
// GET: /Account/RegisterLoyalty
[AllowAnonymous]
public ActionResult RegisterLoyalty()
{
return View();
}
//
// POST: /Account/RegisterLoyalty
[HttpPost]
[AllowAnonymous]
public ActionResult RegisterLoyalty(RegisterLoyaltyViewModel model)
{
var db = new AccountLoyaltyDbContext();
var emailExists = db.Loyalties.Any(x => x.EmailAddress == model.EmailAddress);
if (emailExists)
{
return RedirectToAction("X");
}
db.Loyalties.Add(model);
db.SaveChanges();
return RedirectToAction("Y");
}
//
// GET: /Account/X
[AllowAnonymous]
public ActionResult X()
{
return View();
}
//
// GET: /Account/Y
[AllowAnonymous]
public ActionResult Y()
{
return View();
}
RegisterLoyalty.cshtml
#model UserLoyalty.Models.RegisterLoyaltyViewModel
#{
ViewBag.Title = "RegisterLoyalty";
}
<h2>RegisterLoyalty</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>RegisterLoyaltyViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<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, "", 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>
<div class="form-group">
#Html.LabelFor(model => model.EmailAddress, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EmailAddress, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EmailAddress, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", 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.SecurityQuestion, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SecurityQuestion, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SecurityQuestion, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SecurityAnswer, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SecurityAnswer, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SecurityAnswer, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.optSweepstakes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.optSweepstakes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.optSweepstakes, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.optEmails, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.optEmails, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.optEmails, "", 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>
So here is some code:
Controller
[HttpGet]
public ActionResult GetSettings()
{
var save = new SettingsSaver();
var dto = save.GetSettings();
var model = new SettingsModel
{
Password = dto.Password,
Port = dto.Port,
Username = dto.Username,
Enabled = dto.Enabled,
Id = dto.Id,
IpAddress = dto.IpAddress,
};
return View(model);
}
[HttpPost]
public ActionResult GetSettings(SettingsModel viewModel)
{
if (ModelState.IsValid)
{
var dto = new SettingsDto
{
IpAddress = viewModel.IpAddress,
Password = viewModel.Password,
Port = viewModel.Port,
Username = viewModel.Username,
Enabled = viewModel.Enabled,
Id = viewModel.Id
};
var save = new SettingsSaver();
var result = save.SaveSettings(dto); //Saves correctly and updates in DB
if (result)
{
return View(); // Returns this
}
return View("Error");
}
return View("Error");
}
View (Default Edit View)
#model Dash.UI.Models.Settings.SettingsModel
#{
ViewBag.Title = "Settings";
}
<h2>Settings</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Settings</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.Enabled, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Enabled)
#Html.ValidationMessageFor(model => model.Enabled, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IpAddress, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.IpAddress, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.IpAddress, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Port, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Port, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Port, "", new { #class = "text-danger" })
</div>
</div>
<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.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", 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>
So, what the problem is when I update the model and POST to GetSettings it all works correctly, updates in the db etc. but on the return View() it does not hit the GetSettings() action method, but it returns the view with all of the model filled in except the password.
Model
public class SettingsModel : BaseSettingsViewModel // Base contains ID and Enabled properties with no data annotations
{
[Required]
[DataType(DataType.Text)]
[DisplayName("IP Address")]
public string IpAddress { get; set; }
[Required]
[DisplayName("Port")]
public int Port { get; set; }
[Required]
[DataType(DataType.Text)]
[DisplayName("Username")]
public string Username { get; set; }
[Required]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string Password { get; set; }
}
Any advise/guidance would be much appreciated.
Upon returning the same view from a POST, the ModelState will fill in the controls (apart from the password fields) from the posted values.
So you need a Post-Redirect-Get pattern:
if (result)
{
return RedirectToAction("GetSettings");
}