I have a currentPassword property in my changePasswordViewModel and i want to validate it on client side using Remote attribute. this is my model
public class PatientPasswordChangeViewModel
{
public int id { get; set; }
[Required(ErrorMessage ="field is required")]
[DataType(DataType.Password)]
[Remote("IsCorrectPassword", "Patient", ErrorMessage ="Password is incorrect")]
[Display(Name ="Current Password")]
public string OldPassword { get; set; }
[Required(ErrorMessage ="field is required")]
[StringLength(100, ErrorMessage = "The {0} must be atleast {2} characters long", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New Password")]
public string NewPassword { get; set; }
[Required(ErrorMessage ="field is required")]
[DataType(DataType.Password)]
[Compare("NewPassword",ErrorMessage ="Password Does Not Match")]
[Display(Name = "Confirm Password")]
public string ConfirmNewPassword { get; set; }
}
this is RemoteValidation Code in the controller
public JsonResult IsCorrectPassword([Bind(Prefix = "PatientPasswordChangeViewModel.OldPassword")] string OldPassword, [Bind(Prefix = "PatientPasswordChangeViewModel.id")] int id)
{
var getUserName = context.Patients.Where(q => q.p_id == id).Select(q => q.UserName).FirstOrDefault();
var getPassword = context.SiteUsers.Where(q => q.UserName == getUserName).Select(q => q.PasswordHash).FirstOrDefault();
bool status;
if (PasswordHashManager.ValidatePassword(OldPassword, getPassword))
{
status = true;
}
else
{
status = false;
}
return Json(status, JsonRequestBehavior.AllowGet);
}
And this is the View Code
<section class="password_change-body">
<h2 id="passheading">Change Password</h2>
#using (Html.BeginForm("ChangePassword", "Patient", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.HiddenFor(model => model.id)
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.OldPassword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OldPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.OldPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewPassword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NewPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ConfirmNewPassword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ConfirmNewPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ConfirmNewPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="change" class="btn btn-primary" />
</div>
</div>
</div>
}
</section>
I've tried
public JsonResult IsCorrectPassword([Bind(Prefix = "PatientPasswordChangeViewModel")] string OldPassword, [Bind(Prefix = "PatientPasswordChangeViewModel")] int id)
public JsonResult IsCorrectPassword(PatientPasswordChangeViewModel model)
although i'm getting the password value but value for property id is always null. how can i get the value of id.
EDIT
I got it working by using AdditionalValues in Remote Attribute used it in my method.
[Remote("IsCorrectPassword", "Patient", ErrorMessage ="Password is incorrect",AdditionalFields ="id")]
and in my controller method
public JsonResult IsCorrectPassword(string OldPassword, int id)
Related
I want to update user details like Firstname, Lastname and date-of-birth. although the ModelState is valid and SaveChanges doesn't work. I got some errors for ModelState which are about password and email fields.
the error about SaveChanges is about confirmpassword partial class I think that's what errors say!
Error = The function evaluation requires all threads to run.
{"Validation failed for one or more entities. See 'EntityValidationErrors' property for more details."}
here are my files
database UI
database table user with datatype
Registration and password usage
public ActionResult Registration([Bind(Exclude = "IsEmailVerified,ActivationCode")] User user)
{
bool Status = false;
string message = "";
//
// Model Validation
if (ModelState.IsValid)
{
#region //Email is already Exist
var isExist = IsEmailExist(user.EmailID);
if (isExist)
{
ModelState.AddModelError("EmailExist", "ایمیل شما قبلا ثبت شده است");
return View(user);
}
#endregion
#region Generate Activation Code
user.ActivationCode = Guid.NewGuid();
#endregion
#region Password Hashing
user.Password = Crypto.Hash(user.Password);
user.Confirmpassword = Crypto.Hash(user.Confirmpassword); //
#endregion
user.IsEmailVerified = false;
#region Save to Database
using (sitedatabaseEntities1 dc = new sitedatabaseEntities1())
{
dc.Users.Add(user);
dc.SaveChanges();
//Send Email to User
SendVerificationLinkEmail(user.EmailID, user.ActivationCode.ToString());
message = "تبریک ثبت نام شما با موفقیت انجام شد. " +
" و کد فعال سازی برای شما ارسال گردید به ایمیل:" + user.EmailID;
Status = true;
}
#endregion
}
else
{
message = "درخواست نادرست";
}
ViewBag.Message = message;
ViewBag.Status = Status;
return View(user);
}
profile view() usercontroller.cs
public ActionResult profile()
{
using (sitedatabaseEntities1 db = new sitedatabaseEntities1())
{
int userid = int.Parse(Request.Cookies["userid"].Value);
return View(db.Users.Where(x => x.UserID == userid).FirstOrDefault());
}
}
[HttpPost]
public ActionResult profile([Bind(Include = "UserID,FirstName,LastName,DateOfBirth")] User user)
{
var message = "";
if (ModelState.IsValid)
{
if (user != null)
{
var account = db.Users.Where(a => a.UserID == user.UserID).FirstOrDefault();
account.FirstName = user.FirstName;
account.LastName = user.LastName;
account.DateOfBirth = user.DateOfBirth;
db.SaveChanges();
message = "اطلاعات با موفیت ویرایش شد.";
}
else
{
message = "مشکلی در فرایند ویرایش اطلاعات ایجاد شده است.";
}
}
ViewBag.Message = message;
return View();
}
profile.cshtml
#model projectwebsite.Models.User
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.UserID)
<small class="text-muted">#Html.LabelFor(model => model.FirstName)</small>
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "form-text text-danger" })
<hr>
<small class="text-muted">#Html.LabelFor(model => model.LastName)</small>
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "form-text text-danger" })
<hr>
<small class="text-muted">#Html.LabelFor(model => model.DateOfBirth)</small>
#Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DateOfBirth, "", new { #class = "form-text text-danger" })
<button type="submit" value="Save" class="btn btn-success"> submit</button>
if (ViewBag.Message != null)
{
<div class="alert alert-danger">
<strong>error</strong>#ViewBag.Message
</div>
}
}
and last file user.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace projectwebsite.Models
{
[MetadataType(typeof(UserMetadata))]
public partial class User
{
public string Confirmpassword { get; set; }
}
public class UserMetadata
{
[Display(Name="نام")]
[Required(AllowEmptyStrings = false, ErrorMessage = "نام خود را وارد کنید.")]
public string FirstName { get; set; }
[Display(Name ="نام خانوادگی")]
[Required(AllowEmptyStrings = false, ErrorMessage ="نام خانوادگی را وارد کنید.")]
public string LastName { get; set; }
[Display(Name ="ایمیل")]
[Required(AllowEmptyStrings = false, ErrorMessage ="ایمیل خود را وارد کنید")]
[DataType(DataType.EmailAddress)]
public string EmailID { get; set; }
[Display(Name = "تاریخ تولد")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime DateOfBirth { get; set; }
[Display(Name = "پسورد")]
[Required(AllowEmptyStrings =false, ErrorMessage ="پسورد را وارد کنید.")]
[DataType(DataType.Password)]
[MinLength(6,ErrorMessage ="6 حرف کمترین طول پسورد میباشد.")]
public string Password { get; set; }
[Display(Name ="تکرار پسورد")]
[DataType(DataType.Password)]
[Compare("Password",ErrorMessage ="رمز عبور برابر نیست.")]
public string Confirmpassword { get; set; }
}
}
I've found an answer here: Entity Framework/MVC3: temporarily disable validation
By temporarily disabling validation I can bypass other properties validation check.
What I need
I need to add drop down and LabelFor YearID and add from model Year to
current model section with Formate bootstrap as (Replace departID WITH YearID).
I work in MVC 5 visual studio 2015 and i need to get drop down list from another model .
Current model name is Section:
namespace UniversityData.Models
{
[Table("Section")]
public partial class Section
{
public Section()
{
}
[Key]
public int SecID { get; set; }
[Required]
[StringLength(50)]
public string SecName{ get; set; }
[ForeignKey("Department")]
[DisplayName("DepartmentName")]
public int departID { get; set; }
}
}
My code to drop down departID inside my current model section with bootstrapis:
<div class="form-group">
#Html.LabelFor(model => model.departID, "DepartmentName", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("departID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.departID, "", new { #class = "text-danger" })
</div>
</div>
Another model Year I want to generate dropdown to it
[Table("Year")]
public partial class Year
{
public Year()
{
this.department = new HashSet<Department>();
}
[Key]
public int YearID { get; set; }
[Required]
[StringLength(50)]
public string YearName { get; set; }
}
}
what i try as following :
<div class="form-group">
// how to add labelfor replace of text
YearName:
<div class="col-md-10">
#Html.DropDownList("YearID", null, htmlAttributes: new { #class = "form-control" })
</div>
</div>
I get error :
{"DataBinding: 'System.Data.Entity.DynamicProxies.Department_3D49A8148DA2B6C2F8801CE72951BF7FDBF82503B3A52665397F8B7058E3F8A8' does not contain a property with the name 'YearName'."}
Thank you I solved my problem
The problem found in action :
ViewBag.YearID = new SelectList(db.years.ToList(), "YearID", "YearName");
before it found as db.departments.ToList() so that error come after i change departments to years problem solved because drop down for years not department .
And in view i do as following :
<div class="form-group">
#Html.Label("YearName", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("YearID", null, htmlAttributes: new { #class = "form-control" })
</div>
</div>
This is my Model.
public class Territory
{
[Display(Name = "ID", ResourceType = typeof(Resources.Resource))]
public long ID { get; set; }
[Display(Name = "Name", ResourceType = typeof(Resources.Resource))]
public string Name { get; set; }
[Display(Name = "Code", ResourceType = typeof(Resources.Resource))]
public string Code { get; set; }
[Display(Name = "ProviderKey", ResourceType = typeof(Resources.Resource))]
public string ProviderKey { get; set; }
[Display(Name = "Provider", ResourceType = typeof(Resources.Resource))]
public string Provider { get; set; }
[Display(Name = "Countries", ResourceType = typeof(Resources.Resource))]
public virtual IList<Country> Countries { get; set; }
[Display(Name = "Rights", ResourceType = typeof(Resources.Resource))]
public IList<RightApplication> Rights { get; set; }
}
This is my Controller Edit action.
public ActionResult Edit(long id) {
var territory = new db.Territories.FindAsync(id);
if(territory == null) return HttpNotFound();
ViewBag.Countries = new SelectList(db.Countries.AsEnumerable(), "ID", "Name");
return View("Edit", territory);
}
And this is my Index view.
#foreach (var item in Model.Items)
{
<div class="col-lg-2 col-md-3 col-sm-3 col-xs-1">
<h4 class="pull-right" style="margin:4px;"><i class="fa fa-edit"></i>-<i class="fa fa-trash-o"></i></h4>
<div class="panel panel-success territory panel-scroll">
<div class="panel-heading">#item.Name</div>
<div class="panel-body">
<ul class="list-group">
#foreach (var country in item.Countries)
{
<li class="list-group-item">#country.Name</li>
}
</ul>
</div>
</div>
</div>
}
This is my Create View.
#using (Html.BeginForm(htmlAttributes: new { #class = "form single-col" }))
{
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.Name)
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Code)
#Html.EditorFor(model => model.Code)
#Html.ValidationMessageFor(model => model.Code)
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProviderKey)
#Html.EditorFor(model => model.ProviderKey)
#Html.ValidationMessageFor(model => model.ProviderKey)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Provider)
#Html.EditorFor(model => model.Provider)
#Html.ValidationMessageFor(model => model.Provider)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Countries)
#Html.DropDownList("Countries")
</div>
<div class="form-group">
<div class="controls">
<div class="btn-group">
#if (Model.ID == 0)
{
<button type="submit" class="btn btn-primary"><i class="fa fa-plus"></i> Create</button>
}
else
{
<button type="submit" class="btn btn-primary"><i class="fa fa-pencil"></i> Update</button>
}
<a class="btn btn-info" href="#Url.Action("Index")"><i class="fa fa-arrow-left"></i> Back to List</a>
</div>
</div>
</div>
}
I'm trying Country select from DropdownList to show in Index view.I have get Territory Name in index view,but i'm not able to add Country Name in Territory.
there are 2 ways to save the data from the drop down. The first is a little more work and isn't as reliable. Look at the rendered drop down and if there isn't a name on it, add one
#Html.DropDownList("Countries", Model.CountriesList, new { name = "Country" })
with that on your controller you can get the selected value by
Request.Form["Country"].ToString();
the way I would recommend is to change your drop down to a for helper
#Html.DropDownListFor(x => x.Country, Model.CountriesList)
this will tie the selected value to your model (Country in this case) which you can then pull out in your post method
I'm having a little trouble passing url variables to a form on a separate view. Basically I have a 'HomeController' which has a 'Contact' action and view, and a 'SalesController' which has an action and a view called 'View'.
On the view called 'View' (confusing I know), I have an action link like so:
<a href="#Url.Action("Contact", "Home", new { pid = Model.Property[0].Pid, type = "Viewing"})" class="detailsBtn">
As you can see, this is passing two variables of 'pid' and 'type' to the 'Contact' action of the 'HomeController'. The contact returns a strongly typed view with the following model being used.
public class ContactModel
{
[Required]
[DataType(DataType.Text)]
public string FullName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
[Required]
[DataType(DataType.PhoneNumber)]
[Phone(ErrorMessage = "Invalid Phone Number")]
public string Telephone { get; set; }
[DataType(DataType.Text)]
public string Address { get; set; }
[Required]
[DataType(DataType.Text)]
public string Subject { get; set; }
[Required]
[DataType(DataType.Text)]
public string Message { get; set; }
}}
Here's the Contact view:
#using (Html.BeginForm())
{
<div class="formField">
<span class="label">Full Name *</span><br />
#Html.TextBoxFor(Model => Model.FullName, new { #class = "txtContact" })
#Html.ValidationMessageFor(Model => Model.FullName, "Full enter your full name")<br/>
</div>
<div class="formField">
<span class="label">Email Address *</span><br />
#Html.TextBoxFor(Model => Model.Email, new { #class = "txtContact" })
#Html.ValidationMessageFor(Model => Model.Email, "Please ensure that a valid email is entered.")<br/>
</div>
<div class="formField">
<span class="label">Telephone *</span><br />
#Html.TextBoxFor(Model => Model.Telephone, new { #class = "txtContact" })
#Html.ValidationMessageFor(Model => Model.Telephone, "Please enter a valid telephone number")<br/>
</div>
<div class="formField">
<span class="label">Property Address (optional)</span><br />
#Html.TextBoxFor(Model => Model.Address, new {#class = "txtContact" })<br />
</div>
<div class="formField">
<span class="label">Subject *</span><br />
#if (ViewBag.Pid != null) {
#Html.TextBoxFor(Model => Model.Subject, new {#class = "txtContact" })
} else {
#Html.TextBoxFor(Model => Model.Subject, new { #class = "txtContact" })
}
#Html.ValidationMessageFor(Model => Model.Subject, "Please enter a subject")<br/>
</div>
<div class="formField">
<span class="label">Message *</span><br />
#Html.TextAreaFor(Model => Model.Message, new { #class = "txtContact" })
#Html.ValidationMessageFor(Model => Model.Message, "Please enter a message")<br/>
</div>
<input type="submit" class="contact-btn" value="Send" />
}
I simply need to know the best way for me to add the 'pid' and 'type' variables passed to the Contact Action from the Action link in the Sales Controller as values for my text boxes in the contact form.
You can always extend your Model to include a PID and Type property.
In your form you could just enter #Html.HiddenFor(Model => model.Pid) and #Html.HiddenFor(Model => model.Type) (or #Html.DisplayFor if you want them visible)
If you didn't want to do that, you could put your PID and Type values into ViewBag or ViewData from the Action, and then put these values into form fields in your view.
Edit:
If you would like the Pid and Type to be part of your strongly typed view, you can change your model to be like the following:
public class ContactModel
{
//all your other properties...
public string ContactType { get; set; }
public string Pid { get; set; }
}
Then in your Contact action, you can:
var model = new ContactModel() { ContactType = type, Pid = pid };
return View(model);
I have a question about using a dropdownlist in ASP.net MVC.
This is my situation:
Create view:
#using (Html.BeginForm("Create", "Deliverable", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>EventViewModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Thumbnail)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Thumbnail, new { type = "file" })
#Html.ValidationMessageFor(model => model.Thumbnail)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Image)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Image , new {type="file"})
#Html.ValidationMessageFor(model => model.Image)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.VideoUrl)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.VideoUrl)
#Html.ValidationMessageFor(model => model.VideoUrl)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.VideoUrl)
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.VideoUrl)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
After the 'VideoURL' I would like to have a Dropdownlist with values that are stored in my database. Most of the tutorials that I find don't bind the values in the dropdownlist to the database.
I insert the values in my db in my backoffice so I can't insert them in frontoffice...
This is my Controller:
public ActionResult Create(DeliverableViewModel model)
{
var afstudeerrichtingen = (repository.GetAfstudeerrichtingen()).ToList();
if (ModelState.IsValid)
{
try
{
MemoryStream target = new MemoryStream();
model.Image.InputStream.CopyTo(target);
byte[] data = target.ToArray();
model.Thumbnail.InputStream.CopyTo(target);
byte[] datatwo = target.ToArray();
users usr = userrepo.FindByUsername(User.Identity.Name);
model.UsernameID = usr.user_id;
repository.AddDeliverable(model.Title, model.Description, model.UsernameID, data, datatwo, model.VideoUrl, model.Afstudeerrichting);
}
catch (ArgumentException ae)
{
ModelState.AddModelError("", ae.Message);
}
return RedirectToAction("Index");
}
return View(model);
}
In sent the values to my repository where I save it in my database.
This is my DeliverableViewModel:
public class DeliverableViewModel
{
[Required]
[Display(Name = "Title")]
public string Title { get; set; }
[Required]
[Display(Name = "Description")]
public string Description { get; set; }
[Required]
[Display(Name = "Thumbnail")]
public HttpPostedFileBase Thumbnail { get; set; }
[Required]
[Display(Name = "Image")]
public HttpPostedFileBase Image { get; set; }
[Required]
[Display(Name = "VideoUrl")]
public string VideoUrl { get; set; }
[Required]
[Display(Name = "AfstudeerrichtingID")]
public int AfstudeerrichtingID { get; set; }
[Required]
[Display(Name = "Afstudeerrichting")]
public IEnumerable<SelectListItem> Items { get; set; }
public long UsernameID { get; set; }
}
Does anyone know what I have to add in my view & controller to make this work?
The values are in my tabel "Afstudeerrichtingen" in my mysql database
- afstuddeerichting_id
- afstudeerrichting_name
Add a dropdownlist in your view:
#Html.DropDownListFor(model => model.AfstudeerrichtingID,
new SelectList(ViewBag.Richtingen,
"AfstudeerrichtingId", "AfstudeerrichtingName"))
Add your Afstudeerrichting collection to the ViewBag in the controller:
ViewBag.Richtingen = afstudeerrichtingen;
Assuming that that collection contains the properties AfstudeerrichtingId and AfstudeerrichtingName, as used in the view.
Another thing to do is change your AfstudeerrichtingID to string, and translate it to/from int in your repository class.