Mark Radio Button as Selected ASP.NET MVC5 C# - c#

I have a page written using some fake data in my controller, to render some mock data in my view. Here is the code I have:
Model
Data View Model
[Required]
[Display(Name = "Is this a remix?")]
public bool IsRemix { get; set; }
[Required]
[Display(Name = "Does this song contain sample(s)?")]
public bool ContainsSample { get; set; }
I had this in my ViewModel
public bool IsRemix { get; set; }
public bool ContainsSample { get; set; }
Controller
model.Songs = songs;
model.SongTitle = "Darkside of the Moon";
model.AlternativeSongTitle = "Wish You Were Here";
model.DurationMinutes = 3;
model.DurationSeconds = 57;
model.IsRemix = true;
model.ContainsSample = false;
View
<div class="form-group">
<label class="control-label col-md-4 pull-left" for="SongTitle">Is a Remix</label>
<div class="col-md-8">
<div class="admin-form theme-primary">
<div class="radio-custom radio-primary mt10 mr10 pull-left">
#Html.RadioButtonFor(m => m.IsRemix, true, new { #class = "control-label col-md-4" })
<label for="IsRemixYes">Yes</label>
</div>
<div class="radio-custom radio-primary mt10 pull-left">
#Html.RadioButtonFor(m => m.IsRemix, true, new { #class = "control-label col-md-4" })
<label for="IsRemixNo">No</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4 pull-left" for="SongTitle">Contains Sample</label>
<div class="col-md-8">
<div class="admin-form theme-primary">
<div class="radio-custom radio-primary mt10 mr10 pull-left">
#Html.RadioButtonFor(m => m.ContainsSample, true, new { #class = "control-label col-md-4" })
<label for="ContainsSampleYes">Yes</label>
</div>
<div class="radio-custom radio-primary mt10 pull-left">
#Html.RadioButtonFor(m => m.ContainsSample, true, new { #class = "control-label col-md-4" })
<label for="ContainsSampleNo">No</label>
</div>
</div>
</div>
</div>
I am unsure how to get the radio buttons to be pre-selected.

Related

Create new Application User After Submitting Form in ASP.NET MVC

I have gone through my code several times and still cannot figure what I might be doing wrong.
In my ASP.NET MVC Application, I want to be able to create a new user after a form has being submitted through the View Model. Part of the information submitted through the view model will be used to Populate the ApplicationUser Model.
Here is my View Model
[Column(TypeName = "decimal(18,2)")]
[Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
[Display(Name = "LoanAmount", ResourceType = typeof(Resources))]
public decimal LoanAmount { get; set; }
[Display(Name = "LoanPurpose", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
public LoanPurpose LoanPurpose { get; set; }
[Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
[Display(Name = "FirstName", ResourceType = typeof(Resources))]
public string FirstName { get; set; }
[Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
[Display(Name = "LastName", ResourceType = typeof(Resources))]
public string LastName { get; set; }
[Display(Name = "DateOfBirth", ResourceType = typeof(Resources))]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
[Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
public DateTime? DateOfBirth { get; set; }
[Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
[Display(Name = "StreetAddress", ResourceType = typeof(Resources))]
public string Street { get; set; }
[MaxLength(15)]
[Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
[Display(Name = "City", ResourceType = typeof(Resources))]
public string City { get; set; }
[Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
[Display(Name = "State", ResourceType = typeof(Resources))]
public string State { get; set; }
[Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
[Display(Name = "ZIP", ResourceType = typeof(Resources))]
public string ZipCode { get; set; }
[Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
[Display(Name = "Country", ResourceType = typeof(Resources))]
public string Country { get; set; }
[Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
[Display(Name = "Phone", ResourceType = typeof(Resources))]
public string Phone { get; set; }
[Column(TypeName = "decimal(18,2)")]
[Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
[Display(Name = "MonthlyHousingPayment", ResourceType = typeof(Resources))]
public decimal MonthlyHousingPayment { get; set; }
[Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
[Display(Name = "EmploymentStatus", ResourceType = typeof(Resources))]
public EmploymentStatus EmploymentStatus { get; set; }
[Column(TypeName = "decimal(18,2)")]
[Display(Name = "IndividualYearlyIncome", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
public decimal IndividualYearlyIncome { get; set; }
[Column(TypeName = "decimal(18,2)")]
[Display(Name = "AdditionalYearlyIncome", ResourceType = typeof(Resources))]
public decimal? AdditionalYearlyIncome { get; set; }
[Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
[EmailAddress(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "EmailInvalid")]
[Display(Name = "Email", ResourceType = typeof(Resources))]
public string Email { get; set; }
[Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
[DataType(DataType.Password)]
[StringLength(100, ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "StringLength", MinimumLength = 4)]
[Display(Name = "Password", ResourceType = typeof(Resources))]
public string Password { get; set; }
[Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
[StringLength(20, ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "StringLength", MinimumLength = 4)]
[Display(Name = "Username", ResourceType = typeof(Resources))]
public string UserName { get; set; }
[Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
public bool AcceptCreditReportTerms { get; set; }
public Guid ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
Here is my Controller (CheckRateController)
// POST: CheckRate/Index
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(CheckYourRateViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
FirstName = model.FirstName,
LastName = model.LastName,
UserName = model.UserName,
PhoneNumber = model.Phone,
DateOfBirth = model.DateOfBirth,
State = model.State,
Street = model.Street,
City = model.City,
Country = model.Country
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// Add registered users to Customer role
await _userManager.AddToRoleAsync(user.Id, "Customer");
}
var loanApplication = new Loan
{
LoanPurpose = model.LoanPurpose,
LoanAmount = model.LoanAmount,
EmploymentStatus = model.EmploymentStatus,
MonthlyHousingPayment = model.MonthlyHousingPayment,
IndividualYearlyIncome = model.IndividualYearlyIncome,
AdditionalYearlyIncome = model.AdditionalYearlyIncome,
ApplicationUserId = Guid.Parse(user.Id)
};
db.Loans.Add(loanApplication);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View(model);
}
And this is How my View Starts (Index.cshtml)
<section class="main-chkout">
<div class="container">
#using (Html.BeginForm("Index", "CheckRate", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<h1>#Resources.CheckYourRate</h1>
<div class="col-md-8 col-sm-8 col-xs-12">
<div class="frm-bx">
<h2>How much would you like to borrow?</h2>
<div class="frm-gap">
<div class="row">
<div class="col-md-4 col-sm-4 col-xs-12">
<div class="inp-sty1">
#Html.LabelFor(m => m.LoanAmount)
</div>
</div>
<div class="col-md-8 col-sm-8 col-xs-12">
<div class="inp-sty lgap">
#Html.TextBoxFor(m => m.LoanAmount, new { placeholder = #Resources.LoanAmount })
<span>$</span>
</div>
#Html.ValidationMessageFor(model => model.LoanAmount, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-4 col-sm-4 col-xs-12">
<div class="inp-sty1">
#Html.LabelFor(m => m.LoanPurpose)
</div>
</div>
<div class="col-md-8 col-sm-8 col-xs-12">
<div class="inp-sty">
#Html.EnumDropDownListFor(model => model.LoanPurpose)
<i class="fa fa-caret-down" aria-hidden="true"></i>
</div>
#Html.ValidationMessageFor(model => model.LoanPurpose, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div> <!-- Form tab End -->
<div class="frm-bx">
<h2>Tell Us About Yourself</h2>
<div class="frm-gap">
<div class="row">
<div class="col-md-4 col-sm-4 col-xs-12">
<div class="inp-sty1">
<label for="">Full Name</label>
</div>
</div>
<div class="col-md-8 col-sm-8 col-xs-12">
<div class="row">
<div class="col-md-6">
<div class="inp-sty">
#Html.TextBoxFor(m => m.FirstName, new { placeholder = #Resources.FirstName })
</div>
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
<div class="col-md-6">
<div class="inp-sty">
#Html.TextBoxFor(m => m.LastName, new { placeholder = #Resources.LastName })
</div>
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 col-sm-4 col-xs-12">
<div class="inp-sty1">
#Html.LabelFor(m => m.DateOfBirth)
</div>
</div>
<div class="col-md-8 col-sm-8 col-xs-12">
<div class="inp-sty">
#Html.TextBoxFor(m => m.DateOfBirth, new { placeholder = "Date of Birth (MM/DD/YYYY)" })
</div>
#Html.ValidationMessageFor(model => model.DateOfBirth, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-4 col-sm-4 col-xs-12">
<div class="inp-sty1">
#Html.LabelFor(m => m.Street)
</div>
</div>
<div class="col-md-8 col-sm-8 col-xs-12">
<div class="inp-sty">
#Html.TextBoxFor(m => m.Street, new { placeholder = #Resources.StreetAddress })
</div>
#Html.ValidationMessageFor(model => model.Street, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-4 col-sm-4 col-xs-12">
<div class="inp-sty1">
<label for="">City & State</label>
</div>
</div>
<div class="col-md-8 col-sm-8 col-xs-12">
<div class="row">
<div class="col-md-6">
<div class="inp-sty">
#Html.TextBoxFor(m => m.City, new { placeholder = #Resources.City })
</div>
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
<div class="col-md-6">
<div class="inp-sty">
<div class="inp-sty">
#Html.TextBoxFor(m => m.State, new { placeholder = #Resources.State })
</div>
#Html.ValidationMessageFor(model => model.State, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 col-sm-4 col-xs-12">
<div class="inp-sty1">
<label for="">Zip & Phone</label>
</div>
</div>
<div class="col-md-8 col-sm-8 col-xs-12">
<div class="row">
<div class="col-md-6">
<div class="inp-sty">
#Html.TextBoxFor(m => m.ZipCode, new { placeholder = #Resources.ZIP })
</div>
#Html.ValidationMessageFor(model => model.ZipCode, "", new { #class = "text-danger" })
</div>
<div class="col-md-6">
<div class="inp-sty">
#Html.TextBoxFor(m => m.Phone, new { placeholder = #Resources.PhoneNumber })
</div>
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div> <!-- Row End -->
<div class="row">
<div class="col-md-4 col-sm-4 col-xs-12">
<div class="inp-sty1">
#Html.LabelFor(m => m.MonthlyHousingPayment)
</div>
</div>
<div class="col-md-8 col-sm-8 col-xs-12">
<div class="inp-sty">
#Html.TextBoxFor(m => m.MonthlyHousingPayment, new { placeholder = #Resources.MonthlyHousingPayment })
</div>
#Html.ValidationMessageFor(model => model.MonthlyHousingPayment, "", new { #class = "text-danger" })
</div>
</div> <!-- Row End Here -->
</div>
</div> <!-- Form tab End -->
<div class="frm-bx">
<h2>What is your income?</h2>
<div class="frm-gap">
<div class="row">
<div class="col-md-4 col-sm-4 col-xs-12">
<div class="inp-sty1">
#Html.LabelFor(m => m.EmploymentStatus)
</div>
</div>
<div class="col-md-8 col-sm-8 col-xs-12">
<div class="inp-sty">
#Html.EnumDropDownListFor(model => model.EmploymentStatus)
<i class="fa fa-caret-down" aria-hidden="true"></i>
</div>
#Html.ValidationMessageFor(model => model.EmploymentStatus, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-4 col-sm-4 col-xs-12">
<div class="inp-sty1">
#Html.LabelFor(m => m.IndividualYearlyIncome)
</div>
</div>
<div class="col-md-8 col-sm-8 col-xs-12">
<div class="inp-sty lgap">
#Html.TextBoxFor(m => m.IndividualYearlyIncome, new { placeholder = #Resources.IndividualYearlyIncome })
<span>$</span>
</div>
#Html.ValidationMessageFor(model => model.IndividualYearlyIncome, "", new { #class = "text-danger" })
</div>
</div> <!-- Row End Here -->
<div class="row">
<div class="col-md-4 col-sm-4 col-xs-12">
<div class="inp-sty1">
#Html.LabelFor(m => m.AdditionalYearlyIncome)
</div>
</div>
<div class="col-md-8 col-sm-8 col-xs-12">
<div class="inp-sty lgap">
#Html.TextBoxFor(m => m.AdditionalYearlyIncome, new { placeholder = #Resources.AdditionalYearlyIncome })
<span>$</span>
</div>
#Html.ValidationMessageFor(model => model.AdditionalYearlyIncome, "", new { #class = "text-danger" })
</div>
</div> <!-- Row End Here -->
</div>
</div> <!-- Form tab End -->
<div class="frm-bx">
<h2>Save your information</h2>
<div class="frm-gap">
<div class="row">
<div class="col-md-4 col-sm-4 col-xs-12">
<div class="inp-sty1">
#Html.LabelFor(m => m.Email)
</div>
</div>
<div class="col-md-8 col-sm-8 col-xs-12">
<div class="inp-sty">
#Html.TextBoxFor(m => m.Email, new { placeholder = #Resources.Email })
</div>
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-4 col-sm-4 col-xs-12">
<div class="inp-sty1">
#Html.LabelFor(m => m.UserName)
</div>
</div>
<div class="col-md-8 col-sm-8 col-xs-12">
<div class="inp-sty">
#Html.TextBoxFor(m => m.UserName, new { placeholder = #Resources.Username })
</div>
#Html.ValidationMessageFor(model => model.UserName, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-4 col-sm-4 col-xs-12">
<div class="inp-sty1">
#Html.LabelFor(m => m.Password)
</div>
</div>
<div class="col-md-8 col-sm-8 col-xs-12">
<div class="inp-sty">
#Html.PasswordFor(m => m.Password, new { placeholder = #Resources.Password })
</div>
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div> <!-- Form tab End -->
</div> <!-- col-md-8 End -->
<div class="col-md-4 col-sm-4 col-xs-12">
<div class="chklst">
<ul>
<li>
<img src="~/Content/assets/images/stopwatch.svg" alt="">
<p>Check your rate in<br> 5 minutes</p>
</li>
<li>
<img src="~/Content/assets/images/percent.svg" alt="">
<p>Get lower rates</p>
</li>
<li>
<img src="~/Content/assets/images/wallet.svg" alt="">
<p>Single monthly payments</p>
</li>
<li>
<img src="~/Content/assets/images/calendar2.svg" alt="">
<p>Fixed terms—3 or 5 years*</p>
</li>
</ul>
</div>
</div>
<div class="clear"></div>
<div class="chl-txt">
<p>The following documents contain important information, including your agreement to do business with<br> <span>Lendy</span> electronically. <span>By clicking the box below, you confirm that you agree by electronic signature to:</span></p>
</div>
<label class="checke">
the Credit Report Authorization, Terms of Use and Electronic Consent, Data Terms of Use & Prosper privacy policies.
#Html.CheckBoxFor(m => m.AcceptCreditReportTerms)
<span class="checkmark"></span>
</label>
#Html.ValidationMessageFor(model => model.AcceptCreditReportTerms, "", new { #class = "text-danger" })
<input type="submit" class="btncus" value="Check your rates" />
</div>
}
</div>
Try updating BeginForm to look something like this...
Html.BeginForm("Index", "Home", FormMethod.Post)
I have noticed that you are checking whether the model state is valid or not in the controller method using 'ModelState.IsValid' property with if condition and all your code inside that if condition.
Check by adding a breakpoint to this location to check whether your submitted form model is valid or not at this point if it's false then your data will not be saved according to your logic.
Another thing is to make sure while using 'ModelState.IsValid' is that you are not posting invalid data for the particular field like if you have added validation for a decimal field in your view model and in form you are using 'TextBoxFor' tag helper for that particular field which accepts any characters and same for other data types also so make sure you are posting right data to controller otherwise 'ModelState.IsValid' will be false.

How to upload an image using entity framework C# mvc?

I'm using ASP.NET c# mvc with entity framework to build a web site. So I want to create user profile for the registered user which is editable. Within that i have coded for a image upload part and it was not successfully worked out for me.
This is my View file (Manage.cshtml)
#model TheFoody.Models.ManageViewModel
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script>
function editFunc() {
document.getElementById("Photo").disabled = false;
document.getElementById("FirstName").disabled = false;
document.getElementById("LastName").disabled = false;
document.getElementById("Email").disabled = false;
document.getElementById("UserType").disabled = false;
document.getElementById("Address").disabled = false;
document.getElementById("City").disabled = false;
document.getElementById("District").disabled = false;
document.getElementById("Phone").disabled = false;
//document.getElementById("Photo").disabled = false;
document.getElementById("PostCode").disabled = false;
document.getElementById("Status").disabled = false;
}
function reload() {
window.location.href = "http://localhost:1672/Manage";
}
</script>
<div class="breadcrumb-wrapper">
<div class="container">
<ol class="breadcrumb-list booking-step">
<li>Home</li>
<li><span>User Profile</span></li>
</ol>
</div>
</div>
<div class="admin-container-wrapper">
<div class="container">
<div class="GridLex-gap-15-wrappper">
<div class="GridLex-grid-noGutter-equalHeight">
<div class="GridLex-col-3_sm-4_xs-12">
<div class="admin-sidebar">
<div class="admin-user-item">
<div class="image">
<img src="http://localhost:33409/images/man/01.jpg" alt="image" class="img-circle" />
</div>
<h4>John Doe</h4>
<p class="user-role">Foodies</p>
</div>
<div class="admin-user-action text-center">
Edit
Deactivate
</div>
<ul class="admin-user-menu clearfix">
<li>
<i class="fa fa-tachometer"></i> Dashboard
</li>
<li class="active">
<i class="fa fa-user"></i> Profile
</li>
<li>
<i class="fa fa-key"></i> Change Password
</li>
<li>
<i class="fa fa-bookmark"></i> Favourite Restaurant
</li>
<li>
<i class="fa fa-sign-out"></i> Logout
</li>
</ul>
</div>
</div>
<div class="GridLex-col-9_sm-8_xs-12">
<div class="admin-content-wrapper">
<div class="admin-section-title">
<h2>Profile</h2>
<p>Enquire explain another he in brandon enjoyed be service.</p>
</div>
<!--<form class="post-form-wrapper" action="http://localhost:33409/UpdateProfile/Edit" id="updateForm" method="POST">-->
#using (Html.BeginForm("Manage", "Manage", new { #id = "updateForm", #class = "post-form-wrapper" }, FormMethod.Post))
{
#Html.AntiForgeryToken();
<div class="row gap-20">
<div class="col-sm-6 col-md-4">
#ViewBag.Error
<div class="form-group bootstrap-fileinput-style-01">
<label>Photo</label>
<input type="file" name="Photo" id="Photo" disabled>
#*#Html.HiddenFor(model => model.Photo, new { #class = "form-control", disabled = "disabled" })*#
#*<input type="hidden" value="default" id="photo" name="photo" />*#
<span class="font12 font-italic">** photo must not bigger than 250kb</span>
</div>
</div>
<div class="clear"></div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>First Name</label>
#Html.TextBoxFor(model => model.FirstName, new { #class = "form-control", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>Last Name</label>
#Html.TextBoxFor(model => model.LastName, new { #class = "form-control", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>Email</label>
#*<input type="email" class="form-control" value=Session["UserEmail"].tostring() id="email" name="email" disabled>*#
#Html.TextBoxFor(model => model.Email, new { #class = "form-control", disabled = "disabled"})
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="clear"></div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>Address</label>
#*<input type="text" class="form-control" value="254" id="address" name="address" disabled>*#
#Html.TextBoxFor(model => model.Address, new { #class = "form-control", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="clear"></div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>District</label>
#*<input type="text" class="form-control" value="254" id="district" name="district" disabled>*#
#Html.TextBoxFor(model => model.District, new { #class = "form-control", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.District, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>City/town</label>
#*<input type="text" class="form-control" value="Somewhere " id="city" name="city" disabled>*#
#Html.TextBoxFor(model => model.City, new { #class = "form-control", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>PostCode</label>
#*<input type="text" class="form-control" value="Somewhere " id="postcode" name="postcode" disabled>*#
#Html.TextBoxFor(model => model.PostCode, new { #class = "form-control", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.PostCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>UserType</label>
</div>
<div class="col-sm-6 col-md-4">
#{
List<SelectListItem> listItemsUserType = new List<SelectListItem>();
listItemsUserType.Add(new SelectListItem
{
Text = "Admin",
Value = "Admin"
});
listItemsUserType.Add(new SelectListItem
{
Text = "Customer",
Value = "Customer",
Selected = true
});
listItemsUserType.Add(new SelectListItem
{
Text = "Business",
Value = "Business"
});
}
#Html.DropDownListFor(model => model.UserType, listItemsUserType, "-- Select Status --", new { #class = "form-control",disabled = "disabled" })
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>Status</label>
</div>
<div class="col-sm-6 col-md-4">
#{
List<SelectListItem> listItemsStatus = new List<SelectListItem>();
listItemsStatus.Add(new SelectListItem
{
Text = "Availble",
Value = "Available",
Selected = true
});
listItemsStatus.Add(new SelectListItem
{
Text = "Not Available",
Value = "Not Available"
});
}
#Html.DropDownListFor(model => model.Status, listItemsStatus, "-- Select Status --", new { #class = "form-control",disabled = "disabled" })
</div>
</div>
<div class="clear"></div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>Phone Number</label>
#*<input type="text" class="form-control" value="+66-85-221-5489" id="phone" name="phone" disabled>*#
#Html.TextBoxFor(model => model.Phone, new { #class = "form-control", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
<div class="clear"></div>
<div class="col-sm-12 mt-10">
#*<input type="submit" onclick="document.getElementById('updateform').submit()" class="btn btn-primary" value="Save" />*#
<input type="submit" class="btn btn-primary" value="Save" />
Cancel
</div>
</div>
}
<!--</form>-->
</div>
</div>
</div>
</div>
</div>
</div>
And it will give a UI like below.
And my Model file is like below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace TheFoody.Models
{
public class ManageViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Photo { get; set; }
public string Address { get; set; }
public string City { get; set; }
public int PostCode { get; set; }
public string District { get; set; }
public string UserType { get; set; }
public string Status { get; set; }
}
}
And my Controller looks like this (ManageController.cs)
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TheFoody.DataAccess;
using TheFoody.Models;
namespace TheFoody.Controllers
{
public class ManageController : Controller
{
//ManageContext db = new ManageContext();
//
//GET: /Manage/
public ActionResult Manage()
{
//LoadData();
var manageviewmodel = new ManageViewModel() { Email = Session["UserEmail"].ToString() };
return View(manageviewmodel);
}
private bool isValidContentType(string contentType)
{
return contentType.Equals("Images/png") || contentType.Equals("Images/gif") || contentType.Equals("Images/jpg") || contentType.Equals("Images/jpeg");
}
private bool isValidContentLength(int contentLength)
{
return (contentLength / 1024) / 1024 < 1; //1MB
}
[HttpPost]
public ActionResult Manage(ManageViewModel manageviewmodel, HttpPostedFileBase Photo)
{
TheFoodyContext db = new TheFoodyContext();
User user_to_update = db.Users.SingleOrDefault(s => s.email == manageviewmodel.Email);
if (ModelState.IsValid)
{
try
{
if (!isValidContentType(Photo.ContentType))
{
ViewBag.Error = "Only JPG , JPEG , GIF & PNG are allowed!";
return View("Manage");
}
else if (!isValidContentLength(Photo.ContentLength))
{
ViewBag.Error = "Your File is too Large!";
return View("Manage");
}
else
{
if (user_to_update != null && (Photo != null && Photo.ContentLength > 0))
{
var fileName = Path.GetFileName(Photo.FileName);
var path = Path.Combine(Server.MapPath("~/Content/Images"), fileName);
Photo.SaveAs(path);
user_to_update.email = manageviewmodel.Email;
user_to_update.fname = manageviewmodel.FirstName;
user_to_update.lname = manageviewmodel.LastName;
user_to_update.phone = manageviewmodel.Phone;
//user_to_update.photo = manageviewmodel.Photo;
user_to_update.address = manageviewmodel.Address;
user_to_update.city = manageviewmodel.City;
user_to_update.postcode = manageviewmodel.PostCode;
user_to_update.district = manageviewmodel.District;
user_to_update.user_type = manageviewmodel.UserType;
user_to_update.status = manageviewmodel.Status;
db.SaveChanges();
return RedirectToAction("Manage");
}
}
}
catch (Exception ex)
{
return View("Error");
}
return View(manageviewmodel);
}
return View(manageviewmodel);
}
}
}
And the design of My database is;
And my DbContext file looks as below;
namespace TheFoody.DataAccess
{
using System;
using System.Collections.Generic;
public partial class User
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public User()
{
this.Restaurants = new HashSet<Restaurant>();
}
public string email { get; set; }
public string password { get; set; }
public string fname { get; set; }
public string lname { get; set; }
public string phone { get; set; }
public string photo { get; set; }
public string address { get; set; }
public string city { get; set; }
public Nullable<decimal> postcode { get; set; }
public string district { get; set; }
public string user_type { get; set; }
public string status { get; set; }
public System.DateTime created_date { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Restaurant> Restaurants { get; set; }
}
}
But when i'm executing all these things My ~/Content/Images file does not have the image file that i have uploaded. And it will give me the error to the view as follows.
Actually I wanted to save the path to the relevant image file in the database and image in the ~/Content/Images folder which in following hierarchy.
I'm very new to this environment specially Entity Framework. So i don't know how to correct my code to get what i'm expected.
First you have to do is copy and past that image to your image folder
System.IO.File.Copy("source", "destination");
Then save that path to your data base.

Posting ul elements to a controller

I have a simple email form with TO, CC, BCC and another field for an attachment location i have the view working but i cant workout how to get all 3 ul lists to post to the controller
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-md-2">To</label>
<div class="col-md-10">
<ul name="To" id="email-To"></ul>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Cc</label>
<div class="col-md-10">
<ul name="CC" id="email-Cc"></ul>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Bcc</label>
<div class="col-md-10">
<ul name="Bcc" id="email-Bcc"></ul>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FileName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FileName, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="pull-right">
<button type="submit" class="btn btn-success btn-xs">
<i class="fa fa-save"></i> Create
</button>
</div>
</div>
}
The model:
public System.Guid ID { get; set; }
public string To { get; set; }
public string CC { get; set; }
public string BCC { get; set; }
public string FileName { get; set; }
It will post the filename but not the ul's im guessing i would need to do some kind of json post for this kind of thing im not two sure?

MVC - On post the view model is not getting populated

action method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterViewModel blahblah)
{
HttpPostedFileBase uploadFile;
if (ModelState.IsValid)
{
if (blahblah != null)
{
var obj = new tblPersonalDetail()
{
FirstName = blahblah.FirstName,
LastName = blahblah.LastName,
Title = blahblah.Title,
Address = blahblah.Address,
Suburb = blahblah.Suburb,
HomePhone = blahblah.HomePhone,
Mobile = blahblah.Mobile,
Email = blahblah.Email,
EmergencyName = blahblah.EmergencyContactName,
EmergencyPhone = blahblah.EmergencyContactPhone,
EmergencyEmail = blahblah.EmergencyContactEmail,
EmergencyRelation = blahblah.EmergencyContactRelation,
DrivingLicenceExpiryDate = blahblah.DrivingLicenceExpiryDate,
DrivingLicenceNo = blahblah.DrivingLicenceNo,
DateofBirth = blahblah.DateofBirth
};
//if (uploadFile != null && !string.IsNullOrEmpty(uploadFile.FileName))
//{
// uploadFile.SaveAs(Server.MapPath($#"~\Content\Images\{uploadFile.FileName}"));
// obj.ScannedImageLocation = ($#"~\Content\Images\{uploadFile.FileName}");
//}
db.tblPersonalDetails.Add(obj);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View(blahblah);
}
--registerviewmodel
public class RegisterViewModel
{
public string Title;
public string FirstName;
public string LastName;
public string Address;
public string Suburb;
public string HomePhone;
public string Mobile;
public string Email;
public string EmergencyContactName;
public string EmergencyContactRelation;
public string EmergencyContactPhone;
public string EmergencyContactEmail;
public string DrivingLicenceNo;
// [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime DrivingLicenceExpiryDate;
public string DrivingLicenceImage;
// [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString ="{0:yyyy-MM-dd}")]
public DateTime DateofBirth;
public string Notes;
public string NextAppointment;
public string Name
{
get
{
return $"{FirstName} {LastName}";
}
}
}
the viewmodel on post is all null. if i use the tblPersonalDetail model class generated by the entityframework and then change the reference in the view (Register.cshtml), it posts with the data. However not with the custom view model.
--Register.cshtml
#model Leo.ViewModel.RegisterViewModel
#{
ViewBag.Title = "Register New User";
}
#using (Html.BeginForm("Register", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-md-8">
<div class="panel">
<div class="panel-heading tabbable" tabindex="0"><h1>Personal Details</h1></div>
<div class="panel-body">
<div class="form-group row">
<div class="col-sm-6">
#Html.LabelFor(model => model.Title, "Title", htmlAttributes: new { #class = "control-label" })
<select class="form-control" id="Title">
<option>Mr</option>
<option>Mrs</option>
<option>Dr</option>
<option>Miss</option>
</select>
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
#Html.LabelFor(model => model.FirstName, "First Name", htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-sm-6">
#Html.LabelFor(model => model.LastName, "Last Name", htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
#Html.LabelFor(model => model.Address, "Address", htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Address, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-sm-6">
#Html.LabelFor(model => model.Suburb, "Suburb", htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Suburb, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
#Html.LabelFor(model => model.HomePhone, "Home Phone", htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.HomePhone, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-sm-6">
#Html.LabelFor(model => model.Mobile, "Mobile", htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
#Html.LabelFor(model => model.Email, "Email", htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
</div>
<div class="panel-heading tabbable" tabindex="0"><h1>Emergency Details</h1></div>
<div class="panel-body">
<div class="form-group row">
<div class="col-sm-6">
#Html.LabelFor(model => model.EmergencyContactName, "Name", htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.EmergencyContactName, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-sm-6">
#Html.LabelFor(model => model.EmergencyContactRelation, "Relation", htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.EmergencyContactRelation, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
#Html.LabelFor(model => model.EmergencyContactPhone, "Phone", htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.EmergencyContactPhone, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-sm-6">
#Html.LabelFor(model => model.EmergencyContactEmail, "Email", htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.EmergencyContactEmail, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
</div>
<div class="panel-heading tabbable" tabindex="0"><h1>Driving Licence Details</h1></div>
<div class="panel-body">
<div class="form-group row">
<div class="col-sm-6">
#Html.LabelFor(model => model.DrivingLicenceNo, "Licence No", htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.DrivingLicenceNo, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-sm-6">
#Html.LabelFor(model => model.DrivingLicenceExpiryDate, "Expiry Date", htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.DrivingLicenceExpiryDate, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
#Html.LabelFor(model => model.DrivingLicenceImage, "Licence Image", htmlAttributes: new { #class = "control-label" })
<input type="file" name="uploadFile" />
</div>
<div class="col-sm-6">
#Html.LabelFor(model => model.DateofBirth, "Date of Birth", htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.DateofBirth, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
</div>
<input type="submit" class="btn btn-primary form-control" value="Submit" />
</div>
</div>
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">Notes</div>
<div class="panel-body">
<textarea rows="10" cols="15" class="form-control" id="Notes"></textarea>
</div>
</div>
</div>
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">Invoice</div>
<div class="panel-body">
<div class="form-group row">
<div class="col-sm-6">
<label for="Paid">Paid</label>
<input class="form-control" type="text" id="Paid" placeholder="Amount Paid">
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
<label for="Balance">Balance</label>
<input class="form-control" type="text" id="Balance" placeholder="Balance">
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
<label for="Total">Total</label>
<input class="form-control" type="text" id="Total" placeholder="Total Amount">
</div>
</div>
Print Invoice
</div>
</div>
</div>
</div>
}
You have fields not properties, you need to change your view model definition to have properties like:
public class RegisterViewModel
{
public string Title { get; set;}
public string FirstName { get; set;}
//............
//............
}
The default model binder in ASP.NET MVC will only bind to publicly accessible properties, however you are currently using fields, which will not be bound.
You'll just need to decorate them with the necessary getters / setters as seen below to make them into properties :
public class RegisterViewModel
{
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
// Others omitted for brevity
}

How to generate jQuery template in ASP.NET MVC?

I want to add input to form dynamically with jQuery templates.
My viewModel for rendering form is listed below
public class FormViewModel
{
public int Id { get; set; }
[Required]
[StringLength(25, ErrorMessage = "Max firstname length is 25 symbols.")]
[DisplayName("First name")]
public string FirstName { get; set; }
[Required]
[StringLength(25, ErrorMessage = "Max lastname length is 25 symbols.")]
[DisplayName("Last name")]
public string LastName { get; set; }
[Required]
[Email(ErrorMessage = "Provide correct email address, please.")]
[DisplayName("Email")]
public string Email { get; set; }
[Range(16, 150, ErrorMessage = "Age should be between 16 and 150.")]
[DisplayName("Age")]
public int? Age { get; set; }
public IList<DiscountCode> Discounts { get; set; }
}
This is my model which I use for inputs that will be created dynamically.
public class DiscountCode
{
[Required]
[DisplayName("Code name")]
[StringLength(10, ErrorMessage = "Max name length is 10 symbols.")]
public string Code { get; set; }
[Required]
[DisplayName("Code discount")]
[Integer(ErrorMessage = "The field Percent should be a positive non-decimal number")]
[Range(1,60, ErrorMessage = "The field Percent should be between 1 and 60.")]
public int Percent { get; set; }
}
I have this partial view for rendering DiscountCode inputs
#using DynamicForm.Models
#model FormViewModel
#if (Model != null && Model.Discounts != null)
{
for (int i = 0; i < Model.Discounts.Count; i++)
{
<div class="row">
<input type="hidden" name="Discounts.Index" value="#i" />
<div class="col-md-4 form-group">
<div class="input-group">
#Html.TextBoxFor(m => m.Discounts[i].Code, new { #class = "form-control " })
#Html.ValidationMessageFor(m => m.Discounts[i].Code, string.Empty, new { #class = "help-block" })
</div>
</div>
<div class="col-md-6 form-group">
<div class="input-group">
#Html.LabelFor(m => m.Discounts[i].Percent, new { #class = "control-label" })
#Html.TextBoxFor(m => m.Discounts[i].Percent, new { #class = "form-control " })
#Html.ValidationMessageFor(m => m.Discounts[i].Percent, string.Empty, new { #class = "help-block" })
</div>
</div>
<div class="col-md-2 form-group">
<div class="input-group">
<button type="button" class="btn btn-primary removeDiscountRow">Remove</button>
</div>
</div>
</div>
}
}
And for adding discount inputs I use this code snippet
var data = { index: lastIndex };
var html = $.templates("#discountRow").render(data);
$(html).appendTo($discountsContainer);
and this template
<script id="discountRow" type="text/x-jsrender">
<div class="row">
<input type="hidden" name="Discounts.Index" value="{{: index}}">
<div class="col-md-4 form-group">
<div class="input-group">
<label class="control-label" for="Discounts_{{: index}}__Code">Code name</label>
<input class="form-control " data-val="true" data-val-required="Code is required" data-val-length="Max name length is 10 symbols." data-val-length-max="10"
id="Discounts_{{: index}}__Code" name="Discounts[{{: index}}].Code" type="text" value="">
<span class="field-validation-valid help-block" data-valmsg-for="Discounts[{{: index}}].Code" data-valmsg-replace="true"></span>
</div>
</div>
<div class="col-md-6 form-group">
<div class="input-group">
<label class="control-label" for="Discounts_{{: index}}__Percent">Code discount</label>
<input class="form-control " data-val="true" data-val-required="Percent is required" data-val-number="The field Code discount must be a number."
data-val-range="The field Percent should be between 1 and 60." data-val-range-max="60" data-val-range-min="1"
data-val-regex="The field Percent should be a positive non-decimal number."
data-val-regex-pattern="^-?\d+$" data-val-required="The Code discount field is required."
id="Discounts_{{: index}}__Percent" name="Discounts[{{: index}}].Percent" type="text" value="0" aria-required="true" aria-invalid="false"
aria-describedby="Discounts_{{: index}}__Percent-error">
<span class="help-block field-validation-valid" data-valmsg-for="Discounts[{{: index}}].Percent" data-valmsg-replace="true"></span>
</div>
</div>
<div class="col-md-2 form-group">
<div class="input-group">
<button type="button" class="btn btn-primary removeDiscountRow">Remove</button>
</div>
</div>
</div>
</script>
As you can see I just copy output of razor and insert it in template. So if I change validation in model I'll change template each time. How to generate this template automatic with preserving all data attributes for client-side validation ?
You can generate templte code like you create your input code, but Model.Discounts must have at least one element. See code below. I add DiscountCode to discounts if its empty and change some html attributes to make template display as you want;)
if (Model.Discounts == null || Model.Discounts.Count <= 0)
{
Model.Discounts = new List<DiscountCode> { new DiscountCode() };
}
<script id="discountRow" type="text/x-jsrender">
<div class="row">
<input type="hidden" name="Discounts.Index" value="{{: index}}" />
<div class="col-md-4 form-group">
<div class="input-group">
#Html.LabelFor(m => m.Discounts[0].Percent, new { #class = "control-label", For = "Discounts[{{: index}}].Code" })
#Html.TextBoxFor(m => m.Discounts[0].Code, new { #class = "form-control ", Id = "Discounts_{{: index}}__Code", Name = "Discounts[{{: index}}].Code", Value="" } )
#Html.ValidationMessageFor(m => m.Discounts[0].Code, string.Empty, new { #class = "help-block", Data_Valmsg_For = "Discounts[{{: index}}].Code" })
</div>
</div>
<div class="col-md-6 form-group">
<div class="input-group">
#Html.LabelFor(m => m.Discounts[0].Percent, new { #class = "control-label", For = "Discounts[{{: index}}].Percent" })
#Html.TextBoxFor(m => m.Discounts[0].Percent, new { #class = "form-control ", Id = "Discounts_{{: index}}__Percent", Name = "Discounts[{{: index}}].Percent", Value = "" })
#Html.ValidationMessageFor(m => m.Discounts[0].Percent, string.Empty, new { #class = "help-block", Data_Valmsg_For = "Discounts[{{: index}}].Percent" })
</div>
</div>
<div class="col-md-2 form-group">
<div class="input-group">
<button type="button" class="btn btn-primary removeDiscountRow">Remove</button>
</div>
</div>
</div>
</script>

Categories

Resources