Password value missing after POST - c#

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

Related

ASP.NET - Submitting a form does not pass data

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.

StackOverflowException is caused by a default mvc view

I created a simple create view for a model by mvc's automated way to show to a coleague.
Now, although i do not really use that, i can't see where a recursion is caused since i just said to mvc to create it for a model where all the fields are made with the
"public 'type' 'name' { get; set;}" format. I will include the model, action, and view below.
This isn't really a problem for me since i do not use the templates at all but I am curious how this could happen when no custom code was inserted
Thanks in advance
Controller Action
public ActionResult View()
{
return View();
}
Model
namespace Data_Access.Models
{
public class StudentModel
{
public int studentId { get; set; }
public string name { get; set; }
public string surname { get; set; }
public string classroom { get; set; }
public string role { get; set; }
public string imgPath { get; set; }
}
}
And finally the View
#model Data_Access.Models.StudentModel
#{
ViewBag.Title = "View";
}
<h2>View</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>StudentModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.studentId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.studentId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.studentId, "", new { #class = "text-danger" })
</div>
</div>
<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.surname, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.surname, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.surname, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.classroom, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.classroom, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.classroom, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.role, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.role, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.role, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.imgPath, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.imgPath, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.imgPath, "", 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>
The controller has infinite recursion:
public ActionResult View()
{
return View();
}
Your View() method calls the same View() method ;)
Probably naming problem - I can't suggest any solution here, because you didn't take any information about the flow, what should be implemented in controller.
You can change action name to ViewPage() and add route attribute Route[("View")] above the action.
example:
[Route("View")]
public IActionResult ViewPage()
{
return View();
}
then rename View.cshtml to ViewPage.cshtml
This will prevent recursive and you also use url path /View
I hope this will help you.

Using a file uploader in an editor template

I'm working with documents. I've got working CRUD for DocumentViewModel - good so far. There will be other models that have documents as properties. I don't want to repeat myself, so I converted my Edit View of DocumentViewModel into an editor template.
Now I'm working on LeaseViewModel, which has a property LeaseDocument of type DocumentViewModel. The scaffolded Create view pulls the editor template in correctly. However, I get a problem in the POST Create method in the controller. All the simple LeaseViewModel properties are populated, and most of the sub-properties on the LeaseDocument property are populated, but DocumentUpload is null. Any thoughts?
View Models:
public class DocumentViewModel
{
#region Properties
public int? ItemID { get; set; }
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
public string Description { get; set; }
[Display(Name = "Version Number")]
public int Version_Number { get; set; }
// TODO: culture code?
[Display(Name = "Document")]
[DataType(System.ComponentModel.DataAnnotations.DataType.Upload)]
public HttpPostedFileBase DocumentUpload { get; set; }
...
}
public class LeaseViewModel
{
#region Properties
public int ItemID { get; set; }
[Display(Name = "Space")]
[Required]
public int SpaceID { get; set; }
[Display(Name = "Status")]
[Required]
public int StatusID { get; set; }
public string StatusText { get; private set; }
[Display(Name = "Type")]
[Required]
public int TypeID { get; set; }
public string TypeText { get; private set; }
public DocumentViewModel LeaseDocument { get; set; }
...
}
Controller:
[Authorize]
public class LeasesController : Controller
{
...
// POST: Lease/Create
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(true)]
public ActionResult Create(LeaseViewModel vm)
{
LeaseItem created = createLeaseVersion(vm);
if (created == null)
return View(vm);
else
return RedirectToAction("Index");
}
...
}
View:
#using CMS.CustomTables;
#using CMS.CustomTables.Types.Tenantportal;
#using CMS.DocumentEngine.Types.Tenantportal;
#model TenantPortal.Models.LeaseViewModel
#{
ViewBag.Title = "Documents";
var emptySpaceOpts = new SelectList(new List<CustomTableItem>(), "ItemID", "Identifier");
var tenantOpts = new SelectList(TenantProvider.GetTenants(), "ItemID", "Display_Name");
var statusOpts = new SelectList(CustomTableItemProvider.GetItems<LeaseStatusItem>(), "ItemID", "Name");
var typeOpts = new SelectList(CustomTableItemProvider.GetItems<LeaseTypeItem>(), "ItemID", "Name");
}
<h2 class="page-title">Create Lease</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.EditorFor(model => model.LeaseDocument)
<div class="form-group">
#Html.LabelFor(model => model.SpaceID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SpaceID, emptySpaceOpts, "(select Property)")
#Html.ValidationMessageFor(model => model.SpaceID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StatusID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StatusID, statusOpts)
#Html.ValidationMessageFor(model => model.StatusID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TypeID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.TypeID, typeOpts)
#Html.ValidationMessageFor(model => model.TypeID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ExecutionDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ExecutionDate)
#Html.ValidationMessageFor(model => model.ExecutionDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CommenceDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CommenceDate)
#Html.ValidationMessageFor(model => model.CommenceDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ExpirationDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ExpirationDate)
#Html.ValidationMessageFor(model => model.ExpirationDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CanViewCapBudget, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<label>
#Html.RadioButtonFor(model => model.CanViewCapBudget, "true")
Yes
</label>
<label>
#Html.RadioButtonFor(model => model.CanViewCapBudget, "false", htmlAttributes: new { #checked = "checked" })
No
</label>
#Html.ValidationMessageFor(model => model.CanViewCapBudget, "", 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>
Editor Template for DocumentViewModel
#using TenantPortal.Models
#using CMS.DocumentEngine.Types.Tenantportal
#model DocumentViewModel
#{
var signedOpts = DocumentViewModel.GetSignedOpts();
var propertyOpts = new SelectList(PropertyProvider.GetProperties().Columns("ItemID", "Identifier"), "ItemID", "Identifier");
var tenantOpts = new SelectList(TenantProvider.GetTenants(), "ItemID", "Display_Name");
bool isEdit = ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString() == "Edit";
object uploaderAtts;
int version;
if (isEdit)
{
uploaderAtts = new { #type = "file", #class = "form-control" };
Model.Version_Number += 1;
version = Model.Version_Number;
}
else
{
uploaderAtts = new { #type = "file", #required = "required", #class = "form-control" };
version = 1;
}
}
#Html.HiddenFor(model => model.ItemID)
<div class="form-group row">
<div class="col-sm-12 col-md-6 field">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
<div class="col-sm-12 col-md-6 field">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group row">
<div class="col-sm-12 col-md-6 field">
#Html.LabelFor(model => model.Version_Number, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Version_Number, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly", #Value = version } })
#Html.ValidationMessageFor(model => model.Version_Number, "", new { #class = "text-danger" })
</div>
<div class="col-sm-12 col-md-6 field">
#Html.LabelFor(model => model.DocumentUpload, htmlAttributes: new { #class = "control-label" })
#(isEdit ? Html.Raw(String.Format("<a href='{0}' download='{1}'>{1}</a>", Model.Document_Url, Model.Original_File_Name)) : new HtmlString(""))
#Html.TextBoxFor(model => model.DocumentUpload, uploaderAtts)
#Html.ValidationMessageFor(model => model.DocumentUpload, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group row">
<div class="col-sm-12 col-md-4 field">
#Html.LabelFor(model => model.Signed, htmlAttributes: new { #class = "control-label" })
#Html.DropDownListFor(model => model.Signed, signedOpts, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Signed, "", new { #class = "text-danger" })
</div>
<div class="col-sm-12 col-md-4 field">
#Html.LabelFor(model => model.PropertyID, htmlAttributes: new { #class = "control-label" })
#Html.DropDownListFor(model => model.PropertyID, propertyOpts, "(none)")
#Html.ValidationMessageFor(model => model.PropertyID, "", new { #class = "text-danger" })
</div>
<div class="col-sm-12 col-md-4 field">
#Html.LabelFor(model => model.TenantID, htmlAttributes: new { #class = "control-label" })
#Html.DropDownListFor(model => model.TenantID, tenantOpts, "(none)")
#Html.ValidationMessageFor(model => model.TenantID, "", new { #class = "text-danger" })
</div>
</div>
If your form is sending a file, you have to set its enctype to multipart/form-data
e.g.
#using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
Hth...

MVC Registration with details

I have a bit of a problem, When a user registers on my site they put in email/password then go onto another for for there details, addres etc, however after inputting details and pressing save it flips straight back to the initial login saying "enter email" "enter password" so it doesn't save the customers details only email/password. Here is my controller-
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// Comment the following line to prevent log in until the user is confirmed.
// await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account");
ViewBag.Message = "Check your email and confirm your account, you must be confirmed "
+ "before you can log in.";
return View("Create");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
// GET: Create
public ActionResult Create()
{
return View();
}
// POST: Customers/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 = "CustomerId,AccountId,FirstName,LastName,Address,City,PostalCode,Country,Phone,Mobile")] Customer customer)
{
ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
customer.AccountId = user.Id;
db.Customers.Add(customer);
db.SaveChanges();
return View("Index");
}
Here is my customer Model -
public class Customer
{
[ScaffoldColumn(false)]
public string AccountId { get; set; }
[Key]
[ScaffoldColumn(false)]
public int CustomerId { get; set; }
[Required]
[StringLength(16, ErrorMessage = "Your name is too long")]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Your last name is required.")]
[StringLength(16, ErrorMessage = "Last name is too long.")]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required(ErrorMessage = "Address is required.")]
public string Address { get; set; }
[Required(ErrorMessage = "City is required.")]
public string City { get; set; }
[Required(ErrorMessage = "Postcode is required.")]
[Display(Name = "Post Code")]
public string PostalCode { get; set; }
[Required(ErrorMessage = "Country is required.")]
public string Country { get; set; }
[Required(ErrorMessage = "Phone home number is required.")]
[Display(Name = "Home Telephone")]
public string Phone { get; set; }
[Required(ErrorMessage = "Phone mobile number is required.")]
[Display(Name = "Mobile")]
public string Mobile { get; set; }
}
And my Razor view -
#model T_shirt_Company_v3.Models.RegisterViewModel
#{
ViewBag.Title = "Register";
}
<h2>#ViewBag.Title.</h2>
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.Email, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.ConfirmPassword, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Register" />
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
"Create" part to add details - view
#model T_shirt_Company_v3.Models.Customer
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Customer</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.Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.City, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PostalCode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PostalCode, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PostalCode, "", 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>
<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.Mobile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Mobile, "", 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>

How do I put the values of a model into a database table, from inside a controller?

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>

Categories