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>
Related
I have been trying to validate an input which is not properly in the model. I have the following code:
#using (Html.BeginForm("Address", "Locations", FormMethod.Post, new { id =
"mainForm" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="card shadow-sm">
<div class="card-header">
<h3 class="card-title">
Step 1
</h3>
<label>
Search for service location(s)
</label>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="exampleInputEmail1">Zip code: <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="ZipCode" name="ZipCode" autocomplete="off" autofocus />
#Html.ValidationMessage("ZipCode")
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="exampleInputPassword1">House number:</label>
<input type="text" class="form-control" id="HouseNumber" name="HouseNumber" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="exampleInputPassword1">City:</label>
<input type="text" class="form-control" id="City" name="City" />
</div>
</div>
</div>
</div>
<div class="card-footer">
<div class="row">
<div class="col-md-12">
<button class="btn btn-primary" type="submit">
<i class="fas fa-search"></i>
Search for location(s)
</button>
</div>
</div>
</div>
</div>
}
The mode is
#model PagedList.IPagedList<iCRM.Models.Address>
But the name which I gave to the input is not in the model. However the validation is not working at all. And the POST is ignoring my validation.
Can somebody help me out, what I am doing wrong?
Thanks in advance.
You have 2 options.
add ZipCode to the model class iCRM.Models.Address.
Write custom validation with Request.Forms["ZipCode"] and Javascript handler on client side. (#Html.ValidationMessage("ZipCode") you can not call)
This is idea based on option 2 but not a definite answer.
Controller
[HttpGet]
public ActionResult Address()
{
return View();
}
[HttpPost]
public ActionResult Address(AddressModel model)
{
if (String.IsNullOrEmpty(Request.Form["ZipCode"]))
{
ViewBag.ValidationForZipCode = "Problem with ZipCode";
}
return View();
}
View
#model WebApplication1.Models.AddressModel
#{
ViewBag.Title = "Address";
string strValidationForZipCode = "";
if (ViewBag.ValidationForZipCode != null)
{
strValidationForZipCode = ViewBag.ValidationForZipCode.ToString();
}
}
<h2>Address</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken();
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="pull-right">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</div>
<table>
<tr>
<td>
<div class="form-group">
#Html.LabelFor(model => model.Address1, htmlAttributes: new {
#class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Address1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Zip code: <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="ZipCode" name="ZipCode" autocomplete="off" autofocus />
<input type="hidden" id="hdValidationForZipCode" name="hdValidationForZipCode" value="#strValidationForZipCode" />
</div>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
</div>
}
<script type="text/javascript">
var str1 = document.getElementById("hdValidationForZipCode").value; //$('#hdValidationForZipCode').val();
if (str1 != "")
alert(str1);
</script>
Model
using System.ComponentModel.DataAnnotations;
namespace WebApplication1.Models
{
public class AddressModel
{
[Required]
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
}
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.
I read many of the questions about if(ModelState.IsValid) returns false with error, I also tried this code:
var errors = ModelState.Values.SelectMany(v => v.Errors);
to find what error but it shows no error in it.
But if(ModelState.Isvalid) returns always false. I don't known what mistake I've done in Model, Controller or View.
Model:
public class AdminSignup
{
[Required(ErrorMessage="Contact Person is Required",AllowEmptyStrings=false)]
public string ContactPerson { get; set; }
[Required(ErrorMessage="Email Id is Required",AllowEmptyStrings=false)]
public string EmailId { get; set; }
[Required(ErrorMessage="User Name is Required",AllowEmptyStrings=false)]
public string UserName { get; set; }
[Required(ErrorMessage="Password is Required",AllowEmptyStrings=false)]
public string Password { get; set; }
[Required(ErrorMessage="Apartment Name is Required",AllowEmptyStrings=false)]
public string ApartmentName { get; set; }
[Required(ErrorMessage="Location/City is Required",AllowEmptyStrings=false)]
public string LocationCity { get; set; }
[Required(ErrorMessage="Apartment Address is Required",AllowEmptyStrings=false)]
public string ApartmentAddress { get; set; }
[Required(ErrorMessage="Apartment PhoneNumber is Required",AllowEmptyStrings=false)]
public string ApartmentPhoneNumber { get; set; }
[Required(ErrorMessage="NoOfUnits is Required",AllowEmptyStrings=false)]
public string NoOfUnits { get; set; }
}
Controller:
[HttpPost]
public ActionResult signup(AdminSignup asign)
{
if ( ModelState.IsValid)
{
//SqlConnection con = new SqlConnection(connString);
//con.Open();
//SqlCommand cmd = new SqlCommand("Insert into AdminSignup (ApartmentName,ContactPerson,LocationCity,ApartmentAddress,ApartmentPhoneNumber,EmailId,NoOfUnits) values('" + asign.ApartmentName + "','" + asign.ContactPerson + "','" + asign.LocationCity + "','" + asign.ApartmentAddress + "','" + asign.ApartmentPhoneNumber + "','" + asign.EmailId + "','" + asign.NoOfUnits + "')", con);
//cmd.ExecuteNonQuery();
//AdminSignup adminsignup = new AdminSignup
//{
// EmailId = asign.EmailId
//};
//TempData["EmailId"] = adminsignup;
//con.Close();
return RedirectToAction("SignupStep2");
}
return View();
}
And View :
#using (Html.BeginForm("signup", "Apartment", FormMethod.Post, new { #class = "form-horizontal", #Id = "first-form" }))
{
//#Html.ValidationSummary(false)
<div class="box-body">
<div class="form-group">
<label for="apartment_name" class="col-sm-3 control-label">Apartment Name <sup>*</sup></label>
<div class="col-sm-9">
#* <input class="form-control" id="apartment_name" placeholder="Apartment Name" type="text" name="apartment_name">*#
#Html.TextBoxFor(m => m.ApartmentName, new {#class="form-control",#Id="ApartmentName",placeholder="Apartment Name" })
#Html.ValidationMessageFor(m=>m.ApartmentName)
</div>
</div>
<div class="form-group">
<label for="contact_person" class="col-sm-3 control-label">Contact Person <sup>*</sup></label>
<div class="col-sm-9">
#*<input class="form-control" id="contact_person" placeholder="Password" type="text" name="contact_person">*#
#Html.TextBoxFor(m => m.ContactPerson, new {#class="form-control",#Id="ContactPerson",placeholder="Contact Person" })
#Html.ValidationMessageFor(m=>m.ContactPerson)
</div>
</div>
<div class="form-group">
<label for="loc_city" class="col-sm-3 control-label">Location / City <sup>*</sup></label>
<div class="col-sm-9">
#* <input class="form-control" id="loc_city" placeholder="Location / City" type="text" name="loc_city">*#
#Html.TextBoxFor(m => m.LocationCity, new {#class="form-control",#Id="LocationCity",placeholder="Location/City" })
#Html.ValidationMessageFor(m=>m.LocationCity)
</div>
</div>
<div class="form-group">
<label for="apt_address" class="col-sm-3 control-label">Apartment Address <sup>*</sup></label>
<div class="col-sm-9">
#*<textarea name="apt_address" id="" cols="10" rows="5" class="form-control">Apartment Address</textarea>*#
#Html.TextAreaFor(m => m.ApartmentAddress, new {#class="form-control",#Id="ApartmentAddress" ,placeholder="Apartment Address" })
#Html.ValidationMessageFor(m=>m.ApartmentAddress)
</div>
</div>
<div class="form-group">
<label for="apt_number" class="col-sm-3 control-label">Apartment PhoneNumber <sup>*</sup></label>
<div class="col-sm-9">
#*<input class="form-control" id="apt_number" placeholder="Apartment Number" type="text" name="apt_number">*#
#Html.TextBoxFor(m => m.ApartmentPhoneNumber, new {#class="form-control",#Id="ApartmentPhoneNumber",placeholder="Apartment PhoneNumber" })
#Html.ValidationMessageFor(m=>m.ApartmentPhoneNumber)
</div>
</div>
<div class="form-group">
<label for="apt_emailid" class="col-sm-3 control-lable">Email Id <sup>*</sup></label>
<div class="col-sm-9">
#Html.TextBoxFor(m => m.EmailId, new {#class="form-control",#Id="Email Id",placeholder="EmailId" })
#Html.ValidationMessageFor(m=>m.EmailId)
</div>
</div>
<div class="form-group">
<label for="apt_units" class="col-sm-3 control-label">No of Units <sup>*</sup></label>
<div class="col-sm-9">
#*<input class="form-control" id="apt_units" placeholder="No of Units" type="text" name="apt_units">*#
#Html.TextBoxFor(m => m.NoOfUnits, new {#class="form-control",#Id="NoOfUnits",placeholder="No.Of.Units" })
#Html.ValidationMessageFor(m=>m.NoOfUnits)
</div>
</div>
<div class="form-group text-center">
<input type="submit" value="Next" name="first_form" class="btn btn-info" id="btn_first"/>
</div>
</div>
</div>
Look at your view and model again, you have put required on all your properties within the class, however you are returning 7 of 9 properties. then Model.IsValid will look at your Model and see oh look there 2 required properties that you are not returning, so it will be false. either remove [required] on those properties or add them within your view. good luck.
Update
Those 2 Properties are:
UserName And Password, they need to be within your Html.BeginForm, so they will be send to server as the part of your class.
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.
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?