Asp.Net MVC C# update/edit user model state isnt valid - c#

I have a quick question I am updating my user and there role and my modelstate.isvalid is failing. So the user does not get updated in the database. I don’t have anything [required] that isn’t being entered in a textbox even when I try to enter all fields it still fails. Not sure why.
Here is my data model, my controller action for editing / updating a user and there role and also here is my view with all the controls for inside the view.
Im realy not sure why my modelstate isnt valid i'm not doing anything complicated its just a simple U in CRUD and the action controller isnt validiting the model.
public class UpdateUserViewModel
{
public string UserId { get; set; }
[Display(Name = "User ID")]
public string IdShortened { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[Display(Name = "Username")]
public string UserName { get; set; }
[Display(Name = "Your Name")]
public string Name { get; set; }
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
[DataType(DataType.DateTime),
DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",
ApplyFormatInEditMode = true)]
[Display(Name = "Birthday")]
public DateTime Birthday { get; set; }
[Display(Name = "Date Created")]
public DateTime? DateCreated { get; set; }
[Required]
[Display(Name = "User Roles")]
public string UserRoles { get; set; }
}
public async Task<ActionResult> EditSuperAdmin(string id)
{
if(id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
var user = await manager.FindByIdAsync(id);
if(user == null)
{
return HttpNotFound();
}
var userRoles = await manager.GetRolesAsync(user.Id);
ViewBag.Roles = new SelectList(
context.Roles.ToList(), "Name", "Name");
//new SelectList(context.Roles.Where(u =>
//!u.Name.Contains("SuperAdmin")).ToList(), "Name", "Name");
return View(new UpdateUserViewModel()
{
UserId = user.Id,
IdShortened = user.Id.Substring(0, 10),
Email = user.Email,
UserName = user.UserName,
Name = user.Name,
PhoneNumber = user.PhoneNumber,
Birthday = user.Birthday,
DateCreated = user.DateCreated,
UserRoles = manager.GetRoles(user.Id).FirstOrDefault()
});
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditSuperAdmin([Bind]UpdateUserViewModel model)
{
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
if (ModelState.IsValid)
{
var user = manager.FindById(model.UserId);
if (user == null)
{
return HttpNotFound();
}
user.Email = model.Email;
user.UserName = model.UserName;
user.Name = model.Name;
user.PhoneNumber = model.PhoneNumber;
user.Birthday = model.Birthday;
user.DateCreated = Convert.ToDateTime(model.DateCreated);
var roleResult =
manager.AddToRole(user.Id, model.UserRoles);
if (!roleResult.Succeeded)
{
TempData["ErrorRole"] = "Error adding User Role";
return RedirectToAction("Dashboard");
}
manager.Update(user);
context.SaveChanges();
TempData["Success"] = "User Updated Successfully";
return RedirectToAction("GetAllUsers", "SuperAdmin");
}
TempData["Error"] = "User Update Failed";
return RedirectToAction("Dashboard");
} #model MVC_TimeSh.Models.UpdateUserViewModel
#{
ViewData["Title"] = "Update User";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="text-center">
#if (User.IsInRole("SuperAdmin"))
{
<h2>Update Super Administrator</h2>
}
else
{
<h3>Update | Edit User Account</h3>
}
</div>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(m => m.UserId)
<div class="form-group">
#Html.LabelFor(model => model.IdShortened,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.IdShortened, new { htmlAttributes =
new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.IdShortened, "",
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.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.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.PhoneNumber,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PhoneNumber,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PhoneNumber, "",
new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Birthday,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Birthday,
new { htmlAttributes = new { #class = "form-control datepicker" } })
#Html.ValidationMessageFor(model => model.Birthday, "",
new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DateCreated,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DateCreated, new { htmlAttributes =
new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.DateCreated, "",
new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserRoles,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("UserRoles", (SelectList)ViewBag.Roles, "-- SELECT --")
#*new { htmlAttributes = new { #class = "form-control" } })*#
#Html.ValidationMessageFor(model => model.UserRoles, "",
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-success" />
</div>
</div>
</div>

Sorry don't have 50 reputations can't comment.
As Chetan said debug and check the ModelState errors and check if UserRoles property is the issue.

it will be fine if you go with entity framework. Everything works fine there.

Related

Uploading files from MVC Edit Page/View

I have a very basic mvc project with the standard Edit view & I am trying to add the option to upload a file directly from that view.
I have successfully implemented the upload option from the Create view but it does not work from the Edit view for some reason.
Edit view (file upload and save)
<div class="form-group">
#Html.Label("Attach File", new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" id="file" name="upload" />
</div>
</div>
<div>
<input type="submit" value="Save" class="btn btn-default" />
</div>
Edit Controller
// POST: Travel/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 ActionResult Edit([Bind(Include = "TravelID,RequestedBy,DateRequested,TravelDescription,DestinationCity,DestinationState,StartDate,EndDate,EstRegistrationPerPerson,EstAirfarePerPerson,EstGroundPerPerson,EstLodgingPerPerson,EstMealsPerPerson,DepartureCity,DepartureState,DepartureDate,DepartureTimeRange,ReturnFromCity,ReturnFromState,ReturnFromDate,ReturnFromTimeRange,FlightNote,Hotel,HotelPhone,HotelNote,NeedHotelArrangements,NeedFlightArrangements,NeedRentalCarArrangements,IsTripInTravelBudget,Justification,OtherNote,SupAuth,SupAuthDate,CEOAuth,CEOAuthDate,ActRegistrationPerPerson,ActAirfarePerPerson,ActGroundPerPerson,ActLodgingPerPerson,ActMealsPerPerson")] Travel travel, HttpPostedFileBase upload)
{
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
var file = new Files
{
TravelID = travel.TravelID,
FileName = System.IO.Path.GetFileName(upload.FileName),
FileType = upload.ContentType
};
using (var reader = new System.IO.BinaryReader(upload.InputStream))
{
file.Content = reader.ReadBytes(upload.ContentLength);
}
travel.Files = new List<Files> { file };
}
db.Entry(travel).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Details", "Travel", new { id = travel.TravelID });
}
return View(travel);
}
When I submit the edits, all additional fields update as expected BUT no file is uploaded.
Files Model:
namespace TrainingAndTravel.Models
{
using System;
using System.Collections.Generic;
public partial class Files
{
public int FileID { get; set; }
public int TravelID { get; set; }
public string FileName { get; set; }
public string FileType { get; set; }
public byte[] Content { get; set; }
public virtual Travel Travel { get; set; }
}
}
Travel Model:
namespace TrainingAndTravel.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Travel
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Travel()
{
this.Files = new HashSet<Files>();
this.Travelers = new HashSet<Travelers>();
}
[Display(Name = "Travel ID")]
public int TravelID { get; set; }
[Display(Name = "Requested By")]
public string RequestedBy { get; set; }
[Display(Name = "Date Requested")]
[DisplayFormat(DataFormatString = "{0:g}", ApplyFormatInEditMode = true)]
public System.DateTime DateRequested { get; set; }
[Display(Name = "Travel Description")]
public string TravelDescription { get; set; }
[Display(Name = "Destination City")]
public string DestinationCity { get; set; }
[Display(Name = "Destination State")]
public string DestinationState { get; set; }
[Display(Name = "Start Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> StartDate { get; set; }
[Display(Name = "End Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> EndDate { get; set; }
[Display(Name = "Estimated Registration Per Person")]
public Nullable<decimal> EstRegistrationPerPerson { get; set; }
[Display(Name = "Estimated Airfare Per Person")]
public Nullable<decimal> EstAirfarePerPerson { get; set; }
[Display(Name = "Estimated Ground Per Person")]
public Nullable<decimal> EstGroundPerPerson { get; set; }
[Display(Name = "Estimated Lodging Per Person")]
public Nullable<decimal> EstLodgingPerPerson { get; set; }
[Display(Name = "Estimated Meals Per Person")]
public Nullable<decimal> EstMealsPerPerson { get; set; }
[Display(Name = "Departure City")]
public string DepartureCity { get; set; }
[Display(Name = "Departure State")]
public string DepartureState { get; set; }
[Display(Name = "Departure Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> DepartureDate { get; set; }
[Display(Name = "Departure Time Range")]
public string DepartureTimeRange { get; set; }
[Display(Name = "Return From City")]
public string ReturnFromCity { get; set; }
[Display(Name = "Return From State")]
public string ReturnFromState { get; set; }
[Display(Name = "Return From Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> ReturnFromDate { get; set; }
[Display(Name = "Return From Time Range")]
public string ReturnFromTimeRange { get; set; }
[Display(Name = "Flight Note")]
public string FlightNote { get; set; }
public string Hotel { get; set; }
[Display(Name = "Hotel Phone")]
public string HotelPhone { get; set; }
[Display(Name = "Hotel Note")]
public string HotelNote { get; set; }
[Display(Name = "Need Hotel Arrangements")]
public bool NeedHotelArrangements { get; set; }
[Display(Name = "Need Flight Arrangements")]
public bool NeedFlightArrangements { get; set; }
[Display(Name = "Need Rental Car Arrangements")]
public bool NeedRentalCarArrangements { get; set; }
[Display(Name = "Is Trip In Travel Budget")]
public bool IsTripInTravelBudget { get; set; }
public string Justification { get; set; }
[Display(Name = "Other Note")]
public string OtherNote { get; set; }
[Display(Name = "Supervisor Authorization")]
public string SupAuth { get; set; }
[Display(Name = "Supervisor Authorization Date & Time")]
[DisplayFormat(DataFormatString = "{0:g}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> SupAuthDate { get; set; }
[Display(Name = "CEO Authorization")]
public string CEOAuth { get; set; }
[Display(Name = "CEO Authorization Date & Time")]
[DisplayFormat(DataFormatString = "{0:g}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> CEOAuthDate { get; set; }
[Display(Name = "Actual Registration Per Person")]
public Nullable<decimal> ActRegistrationPerPerson { get; set; }
[Display(Name = "Actual Airfare Per Person")]
public Nullable<decimal> ActAirfarePerPerson { get; set; }
[Display(Name = "Actual Ground Per Person")]
public Nullable<decimal> ActGroundPerPerson { get; set; }
[Display(Name = "Actual Lodging Per Person")]
public Nullable<decimal> ActLodgingPerPerson { get; set; }
[Display(Name = "Actual Meals Per Person")]
public Nullable<decimal> ActMealsPerPerson { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Files> Files { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Travelers> Travelers { get; set; }
}
}
Entire Edit View:
#model TrainingAndTravel.Models.Travel
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit Travel Request</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.TravelID)
<div hidden class="form-group">
#Html.LabelFor(model => model.RequestedBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RequestedBy, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.RequestedBy, "", new { #class = "text-danger" })
</div>
</div>
<div hidden class="form-group">
#Html.LabelFor(model => model.DateRequested, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DateRequested, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.DateRequested, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TravelDescription, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TravelDescription, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TravelDescription, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DestinationCity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DestinationCity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DestinationCity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DestinationState, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DestinationState, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DestinationState, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StartDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StartDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StartDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EndDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EndDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EndDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EstRegistrationPerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EstRegistrationPerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EstRegistrationPerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EstAirfarePerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EstAirfarePerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EstAirfarePerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EstGroundPerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EstGroundPerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EstGroundPerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EstLodgingPerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EstLodgingPerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EstLodgingPerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EstMealsPerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EstMealsPerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EstMealsPerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DepartureCity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DepartureCity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DepartureCity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DepartureState, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DepartureState, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DepartureState, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DepartureDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DepartureDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DepartureDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DepartureTimeRange, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.DepartureTimeRange, TrainingAndTravel.Utils.TimeRangeList.GetTimeRangeList(), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.DepartureTimeRange, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ReturnFromCity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ReturnFromCity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ReturnFromCity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ReturnFromState, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ReturnFromState, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ReturnFromState, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ReturnFromDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ReturnFromDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ReturnFromDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ReturnFromTimeRange, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ReturnFromTimeRange, TrainingAndTravel.Utils.TimeRangeList.GetTimeRangeList(), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ReturnFromTimeRange, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FlightNote, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FlightNote, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FlightNote, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Hotel, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Hotel, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Hotel, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.HotelPhone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HotelPhone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HotelPhone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.HotelNote, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HotelNote, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HotelNote, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Justification, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Justification, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Justification, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OtherNote, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OtherNote, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.OtherNote, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NeedHotelArrangements, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.CheckBoxFor(model => model.NeedHotelArrangements, new { #class = "checkbox" })
#Html.ValidationMessageFor(model => model.NeedHotelArrangements, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NeedFlightArrangements, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.CheckBoxFor(model => model.NeedFlightArrangements, new { #class = "checkbox" })
#Html.ValidationMessageFor(model => model.NeedFlightArrangements, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NeedRentalCarArrangements, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.CheckBoxFor(model => model.NeedRentalCarArrangements, new { #class = "checkbox" })
#Html.ValidationMessageFor(model => model.NeedRentalCarArrangements, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IsTripInTravelBudget, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.CheckBoxFor(model => model.IsTripInTravelBudget, new { #class = "checkbox" })
#Html.ValidationMessageFor(model => model.IsTripInTravelBudget, "", new { #class = "text-danger" })
</div>
</div>
<div hidden class="form-group">
#Html.LabelFor(model => model.ActRegistrationPerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ActRegistrationPerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ActRegistrationPerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div hidden class="form-group">
#Html.LabelFor(model => model.ActAirfarePerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ActAirfarePerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ActAirfarePerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div hidden class="form-group">
#Html.LabelFor(model => model.ActGroundPerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ActGroundPerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ActGroundPerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div hidden class="form-group">
#Html.LabelFor(model => model.ActLodgingPerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ActLodgingPerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ActLodgingPerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div hidden class="form-group">
#Html.LabelFor(model => model.ActMealsPerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ActMealsPerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ActMealsPerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Attach File", new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" id="file" name="upload" />
</div>
</div>
<div>
<input type="submit" value="Save" class="btn btn-default" />
#Html.ActionLink("Cancel", "Details", "Travel", new { id = Model.TravelID }, new { #class = "btn btn-default" })
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
You need to add enctype attribute in form tag on view
View
<form action="" method="post" enctype="multipart/form-data">
<!-- your remaing code-->
<div class="form-group">
#Html.Label("Attach File", new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" id="file" name="upload" />
</div>
</div>
<input type="submit" />
</form>
More Info check here
I had to rearrange my controller a bit, placing the upload portion below the EntityState.Modified and SaveChanges, also needed a db.SaveChanges() below the upload:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "TravelID,RequestedBy,DateRequested,TravelDescription,DestinationCity,DestinationState,StartDate,EndDate,EstRegistrationPerPerson,EstAirfarePerPerson,EstGroundPerPerson,EstLodgingPerPerson,EstMealsPerPerson,DepartureCity,DepartureState,DepartureDate,DepartureTimeRange,ReturnFromCity,ReturnFromState,ReturnFromDate,ReturnFromTimeRange,FlightNote,Hotel,HotelPhone,HotelNote,NeedHotelArrangements,NeedFlightArrangements,NeedRentalCarArrangements,IsTripInTravelBudget,Justification,OtherNote,SupAuth,SupAuthDate,CEOAuth,CEOAuthDate,ActRegistrationPerPerson,ActAirfarePerPerson,ActGroundPerPerson,ActLodgingPerPerson,ActMealsPerPerson")] Travel travel, HttpPostedFileBase upload)
{
if (ModelState.IsValid)
{
db.Entry(travel).State = EntityState.Modified;
db.SaveChanges();
if (upload != null && upload.ContentLength > 0)
{
var file = new Files
{
FileName = System.IO.Path.GetFileName(upload.FileName),
FileType = upload.ContentType
};
using (var reader = new System.IO.BinaryReader(upload.InputStream))
{
file.Content = reader.ReadBytes(upload.ContentLength);
}
travel.Files = new List<Files> { file };
}
db.SaveChanges();
return RedirectToAction("Details", "Travel", new { id = travel.TravelID });
}
return View(travel);
}

C# ASP.NET MVC 5 Entity Framework - edit function did not work

Here is my model:
public class Auction
{
[Key]
[Required]
public long Id { get; internal set; }
[Required]
[Display(Name = "Title")]
public string Title { get; set; }
[Required]
[Display(Name = "Description")]
public string Description { get; set; }
[Required]
[Display(Name = "Product Name")]
public string productName { get; set; }
[Required]
[Display(Name = "Product Price")]
public string productPrice { get; set; }
[Required]
[Display(Name = "Auction Start Time")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy MM, dd}", ApplyFormatInEditMode = true)]
public DateTime StartTime { get; set; }
[Required]
[Display(Name = "Auction End Time")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EndTime { get; set; }
[Required]
[DataType(DataType.Currency)]
[Display(Name = "Auction Start Price")]
public decimal StartPrice { get; set; }
[DataType(DataType.Currency)]
[Display(Name = "Auction Current Price")]
public decimal? CurrentPrice { get; set; }
}
}
Here is my DataContext class:
public class AuctionsDataContext : DbContext
{
public DbSet<Auction> Auctions { get; set; }
static AuctionsDataContext()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<AuctionsDataContext>());
}
}
Here is my View :
#model Mohn.Models.Auction
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Auction</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.Title, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#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">
#Html.LabelFor(model => model.productName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.productName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.productName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.productPrice, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.productPrice, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.productPrice, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StartTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StartTime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StartTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EndTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EndTime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EndTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StartPrice, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StartPrice, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StartPrice, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CurrentPrice, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CurrentPrice, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CurrentPrice, "", 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>
}
And here is my Edit part that does not worked in the controller:
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Auction auction = db.Auctions.Find(id);
if (auction == null)
{
return HttpNotFound();
}
return View(auction);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Title,Description,productName,productPrice,StartTime,EndTime,StartPrice,CurrentPrice")] Auction auction)
{
if (ModelState.IsValid)
{
db.Entry(auction).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(auction);
}
The problem is, when I pass my Auction id in the URL, then it will retrieve data to the view except start time. And I cannot submit the details, it will cause an exception.
Start time will not display on my view,
I am showing a screenshot here:
enter image description here
Even if I submit the start date with given details on my View, it will throw an exception
The screenshot shows it:
enter image description here
An exception of type 'System.Data.Entity.Infrastructure.DbUpdateConcurrencyException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted
Please help me to solve this, and I am new to Asp.net MVC 5, Entity Framework, I want to know what exactly happen...
Thanks your attention....and help..:)
I guess the problem is in the ID...when I debug the program it is passed 0 to the controller...How to change this?...
You need to remove internal for setter method id property. Due to internal model binder was unable to set value to it
[Key]
[Required]
public long Id { get; internal set; }
Change it to
[Key]
[Required]
public long Id { get; set; }
First of all your Start Time format annotation is "{0:yyyy MM, dd}" that seems "{0:yyyy-MM-dd}" is true. after that because of your [DataType(DataType.Currency)] annotation and problem to transfer this field data, this exception has occured.

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>

Password value missing after POST

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

Submitting the form always calls get action method instead of post action method

Hi I've got the following code in my controller (asp.net 4.5.1 mvc 5) that allows a user to register on my site. Everything was working fine but Ive added another controller and another service and now when ever I try to register all it does on submit is redirect back to the form blank again. After debugging, the post action method in controller below is never called
[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)
{
UserManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, model.FirstName));
var service = new GRCMemberService(HttpContext.GetOwinContext().Get<ApplicationDbContext>());
service.CreateGRCMember(model.FirstName, model.LastName, model.Address1, model.Address2, model.City, model.County, model.Postcode, model.Telephone, model.DateOfBirth, model.Dietary, model.CompLicenceNo, model.SelectedLicenceTypeId, model.NOKFirstName, model.NOKLastName, model.NOKTelephone, model.RelationshipTypeId, model.OtherOrgsGRC, model.OtherClubEvents, model.OtherOrgsOutside, user.Id);
//var currentUser = UserManager.FindByName(user.Id);
//var newrole = ("GRCMember");
//var roleresult = UserManager.AddToRole(currentUser.Id, newrole);
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking here");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
instead, the get action method below is always called every time I submit the form:
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
Any idea what's wrong?
Below is my ViewModel and View code.
ViewModel
public class RegisterViewModel
{
[Required]
[Display(Name = "First Name")]
[StringLength(160, ErrorMessage = "First Name cannot be longer than 160 characters.")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
[StringLength(160, ErrorMessage = "Last Name cannot be longer than 160 characters.")]
public string LastName { get; set; }
[Required]
[Display(Name = "Address 1")]
[StringLength(160, ErrorMessage = "Address1 cannot be longer than 160 characters.")]
public string Address1 { get; set; }
[Display(Name = "Address 2")]
[StringLength(160, ErrorMessage = "Address2 cannot be longer than 160 characters.")]
public string Address2 { get; set; }
[Required]
[Display(Name = "City")]
[StringLength(100, ErrorMessage = "City cannot be longer than 100 characters.")]
public string City { get; set; }
[Display(Name = "County")]
[StringLength(100, ErrorMessage = "County cannot be longer than 100 characters.")]
public string County { get; set; }
[Required]
[Display(Name = "PostCode")]
[StringLength(10, ErrorMessage = "Postcode cannot be longer than 10 characters.")]
public string Postcode { get; set; }
[Required]
[Display(Name = "Telephone")]
[StringLength(20, ErrorMessage = "Telephone cannot be longer than 20 characters.")]
public string Telephone { get; set; }
[StringLength(20, ErrorMessage = "Competition Licence Number cannot be longer than 20 characters.")]
[Display(Name = "Licence Number")]
public string CompLicenceNo { get; set; }
[Display(Name = "Licence Type")]
public int? SelectedLicenceTypeId { get; set; }
[StringLength(200, ErrorMessage = "Competition Licence Number cannot be longer than 20 characters.")]
[Display(Name = "Dietary Requirements - For events")]
public string Dietary { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Next of Kin Name cannot be longer than 100 characters.")]
[Display(Name = "Next of kin First Name")]
public string NOKFirstName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Next of Kin Name cannot be longer than 100 characters.")]
[Display(Name = "Next of kin Last Name")]
public string NOKLastName { get; set; }
[Required]
[StringLength(20, ErrorMessage = "Next of Kin Telephone cannot be longer than 20 characters.")]
[Display(Name = "Next of kin Telephone")]
public string NOKTelephone { get; set; }
[Display(Name = "Next of kin Relationship")]
public int? RelationshipTypeId { get; set; }
[Required]
[Display(Name = "Date of Birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/mm/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth { get; set; }
[Display(Name = "Allow other organisations on Grass Roots Clicks to contact you?")]
public bool OtherOrgsGRC { get; set; }
[Display(Name = "Allow other clubs you are a member of or ones whose events you enter to contact you?")]
public bool OtherClubEvents { get; set; }
[Display(Name = "Allow other organisations outside of Grass Roots Clicks that we are working with to contact you?")]
public bool OtherOrgsOutside { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[EmailAddress]
[Display(Name = "Confirm email")]
[Compare("Email", ErrorMessage = "Your email and confirmation email do not match.")]
public string ConfirmEmail { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
View
#model GRCWebApp.Models.RegisterViewModel
#{
ViewBag.Title = "Register";
}
<h2 class="text-success">#ViewBag.Title</h2>
<div class="row">
<div class="col-md-7">
<div class="well bs-component">
<form class="form-horizontal">
<fieldset>
<section id="loginForm">
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<h3 class="text-success col-md-offset-1">Name & Address</h3>
<div class="form-group">
<div class="row">
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control", placeholder = "John" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
<div class="col-md-4 col-md-offset-2">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control", placeholder = "Smith" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-5 col-md-offset-1">
#Html.LabelFor(model => model.Address1, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Address1, new { htmlAttributes = new { #class = "form-control", placeholder = "1 Apple Road" } })
#Html.ValidationMessageFor(model => model.Address1, "", new { #class = "text-danger" })
</div>
<div class="col-md-5">
#Html.LabelFor(model => model.Address2, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Address2, new { htmlAttributes = new { #class = "form-control", placeholder = "Neighbourhood" } })
#Html.ValidationMessageFor(model => model.Address2, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-5 col-md-offset-1">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.City, new { htmlAttributes = new { #class = "form-control", placeholder = "Some Town" } })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
<div class="col-md-5">
#Html.LabelFor(model => model.County, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.County, new { htmlAttributes = new { #class = "form-control", placeholder = "Someshire" } })
#Html.ValidationMessageFor(model => model.County, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.Postcode, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Postcode, new { htmlAttributes = new { #class = "form-control", placeholder = "AA1 2BB" } })
#Html.ValidationMessageFor(model => model.Postcode, "", new { #class = "text-danger" })
</div>
</div>
</div>
<h3 class="text-success col-md-offset-1">Contact Details</h3>
<div class="form-group">
<div class="row">
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.Telephone, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Telephone, new { htmlAttributes = new { #class = "form-control", placeholder = "01234 567890" } })
#Html.ValidationMessageFor(model => model.Telephone, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control", placeholder = "me#provider.com" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.ConfirmEmail, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.ConfirmEmail, new { htmlAttributes = new { #class = "form-control", placeholder = "me#provider.com" } })
#Html.ValidationMessageFor(model => model.ConfirmEmail, "", new { #class = "text-danger" })
</div>
</div>
</div>
<h3 class="text-success col-md-offset-1">Competition Licence</h3>
<div class="form-group">
<div class="row">
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.CompLicenceNo, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.CompLicenceNo, new { htmlAttributes = new { #class = "form-control", placeholder = "123456" } })
#Html.ValidationMessageFor(model => model.CompLicenceNo, "", new { #class = "text-danger" })
</div>
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.SelectedLicenceTypeId, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.SelectedLicenceTypeId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SelectedLicenceTypeId, "", new { #class = "text-danger" })
</div>
</div>
</div>
<h3 class="text-success col-md-offset-1">Personal Details</h3>
<h4 class="text-success col-md-offset-1">Why do we need this information?</h4>
<p>To make it easier for you to enter events here on Grass Roots Clicks we gatther certain information that we can then populate into your entry. Why do we need a date of birth? Organisers gain great benefit form knowing what ages are taking part in their events. We dont share your date of birth, we use your current age to help the organisers and also tailor the entry form to you e.g. if your under 18 we'll ask you for parental permission for some events.</p>
<div class="form-group">
<div class="row">
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { #class = "form-control", placeholder = "01/12/80" } })
#Html.ValidationMessageFor(model => model.DateOfBirth, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.NOKFirstName, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.NOKFirstName, new { htmlAttributes = new { #class = "form-control", placeholder = "Jane" } })
#Html.ValidationMessageFor(model => model.NOKFirstName, "", new { #class = "text-danger" })
</div>
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.NOKLastName, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.NOKLastName, new { htmlAttributes = new { #class = "form-control", placeholder = "Smith" } })
#Html.ValidationMessageFor(model => model.NOKLastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.NOKTelephone, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.NOKTelephone, new { htmlAttributes = new { #class = "form-control", placeholder = "07234 567890" } })
#Html.ValidationMessageFor(model => model.NOKTelephone, "", new { #class = "text-danger" })
</div>
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.RelationshipTypeId, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.RelationshipTypeId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RelationshipTypeId, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-7 col-md-offset-1">
#Html.LabelFor(model => model.Dietary, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Dietary, new { htmlAttributes = new { #class = "form-control", placeholder = "Vegetarian" } })
#Html.ValidationMessageFor(model => model.Dietary, "", new { #class = "text-danger" })
</div>
</div>
</div>
<h3 class="text-success col-md-offset-1">Password</h3>
<div class="form-group">
<div class="row">
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { #class = "text-danger" })
</div>
</div>
</div>
<h3 class="text-success col-md-offset-1">Contact</h3>
<div class="form-group">
<div class="row">
<div class="col-md-9 col-md-offset-1">
#Html.LabelFor(model => model.OtherOrgsGRC, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-1">
#Html.CheckBoxFor(model => model.OtherOrgsGRC, new { #checked = "checked" })
#Html.ValidationMessageFor(model => model.OtherOrgsGRC, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-9 col-md-offset-1">
#Html.LabelFor(model => model.OtherClubEvents, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-1">
#Html.CheckBoxFor(model => model.OtherClubEvents, new { #checked = "checked" })
#Html.ValidationMessageFor(model => model.OtherClubEvents, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-9 col-md-offset-1">
#Html.LabelFor(model => model.OtherOrgsOutside, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-1">
#Html.CheckBoxFor(model => model.OtherOrgsOutside, new { #checked = "checked" })
#Html.ValidationMessageFor(model => model.OtherOrgsOutside, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<input type="submit" value="Register" class="btn btn-success btn-lg" />
</div>
</div>
}
</section>
</fieldset>
</form>
</div>
</div>
<div class="col-md-4 panel panel-success">
<div class="panel-heading">
<h3 class="panel-title " align="center">Use another service to register</h3>
</div>
#Html.Partial("_ExternalLoginsListPartial", new GRCWebApp.Models.ExternalLoginListViewModel { ReturnUrl = ViewBag.ReturnUrl })
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/bootstrap")
<script type="text/javascript">
$("#DateOfBirth").datepicker({
format: "dd/mm/yyyy",
startDate: "-120y",
endDate: "-10y",
startView: 2,
calendarWeeks: true,
defaultViewDate: { year: 1975, month: 01, day: 01 }
});
</script>
}
I fixed the problem by removing the form, fieldset and section tags at the beginning of the view.
Thanks to ekad for helping debug the problem

Categories