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.
Related
I'm trying to do a web App with ASP.NET Core 3.1. I have an existing SQL Database with full of users. I have only read access to this database, so I can't change nothing.
My question is, can I somehow use it to authentication to Login instead of AspNetUsers table?
(I don't need registration, nor forget password, etc., just a safety login)
My User database has these columns: Id(varchar),Name(varchar),Rank(int),Password(varchar),Email(varchar),Phone(varchar)
use it to authentication to Login instead of AspNetUsers table
Below is a demo, you can refer to it.
LoginModel
public class LoginModel
{
[Required]
[Display(Name ="Username")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
public bool RememberLogin { get; set; }
public string ReturnUrl { get; set; }
}
UserModel
public class UserModel
{
public int UserId { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Role { get; set; }
}
AccountController
[Note] I set fake data, you can get it directly from the database.
public class AccountController : Controller
{
//Sample Users Data, it can be fetched with the use of any ORM
public List<UserModel> users = null;
public AccountController()
{
users = new List<UserModel>();
users.Add(new UserModel() { UserId = 1, Username = "Anoop", Password = "123", Role = "Admin" });
users.Add(new UserModel() { UserId = 2, Username = "Other", Password = "123", Role = "User" });
}
public IActionResult Login(string ReturnUrl = "/")
{
LoginModel objLoginModel = new LoginModel();
objLoginModel.ReturnUrl = ReturnUrl;
return View(objLoginModel);
}
[HttpPost]
public async Task<IActionResult> Login(LoginModel objLoginModel)
{
if (ModelState.IsValid)
{
var user = users.Where(x => x.Username == objLoginModel.UserName && x.Password == objLoginModel.Password).FirstOrDefault();
if (user == null)
{
//Add logic here to display some message to user
ViewBag.Message = "Invalid Credential";
return View(objLoginModel);
}
else
{
//A claim is a statement about a subject by an issuer and
//represent attributes of the subject that are useful in the context of authentication and authorization operations.
var claims = new List<Claim>() {
new Claim(ClaimTypes.NameIdentifier,Convert.ToString(user.UserId)),
new Claim(ClaimTypes.Name,user.Username),
new Claim(ClaimTypes.Role,user.Role),
new Claim("FavoriteDrink","Tea")
};
//Initialize a new instance of the ClaimsIdentity with the claims and authentication scheme
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
//Initialize a new instance of the ClaimsPrincipal with ClaimsIdentity
var principal = new ClaimsPrincipal(identity);
//SignInAsync is a Extension method for Sign in a principal for the specified scheme.
//await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
// principal, new AuthenticationProperties() { IsPersistent = objLoginModel.RememberLogin });
await HttpContext.SignInAsync(
principal, new AuthenticationProperties() { IsPersistent = objLoginModel.RememberLogin });
return LocalRedirect(objLoginModel.ReturnUrl);
}
}
return View(objLoginModel);
}
public async Task<IActionResult> LogOut() {
//SignOutAsync is Extension method for SignOut
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
//Redirect to home page
return LocalRedirect("/");
}
}
In HomeController, use [Authorize] on ConfidentialData() method
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[Authorize]
public IActionResult ConfidentialData()
{
return View();
}
}
ConfidentialData view
#{
ViewData["Title"] = "Confidential Data";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Confidential Data</h2>
#if (User.Identity.IsAuthenticated)
{
<table class="table table-bordered">
#foreach (var claim in User.Claims) {
<tr><td>#claim.Type</td><td>#claim.Value</td></tr>
}
</table>
}
Register Authentication in startup
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(x => x.LoginPath = "/account/login");
...
app.UseAuthentication();
app.UseAuthorization();
Result:
Read Use cookie authentication without ASP.NET Core Identity to know more.
Login form
#model LoginModel
#{
ViewData["Title"] = "Login";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Login</h2>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Login">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
#if (!string.IsNullOrEmpty(ViewBag.Message))
{
<span class="text-danger">
#ViewBag.Message
</span>
}
#Html.HiddenFor(x => x.ReturnUrl)
<div class="form-group">
<label asp-for="UserName" class="control-label"></label>
<input asp-for="UserName" class="form-control" />
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password" class="control-label"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input asp-for="RememberLogin" /> #Html.DisplayNameFor(model => model.RememberLogin)
</label>
</div>
</div>
<div class="form-group">
<input type="submit" value="Login" class="btn btn-default" />
</div>
</form>
</div>
</div>
I need to convert this <select id="degreemultiselect" multiple="multiple"></select to a razor control #Html.DropDownList but I am getting the error message it says "cannot convert lambda expression to type string?" is that because of the model being a list public List<DegreeModel> selectedRequesterDegrees { get; set; } is there a work around for this?
#Html.DropDownList(x => x.selectedRequesterDegrees, new { id = "degreemultiselect", #class = "form-control" })
#Html.ValidationMessageFor(model => model.selectedRequesterDegrees)
Here is a working demo:
Model:
public class Test
{
public List<DegreeModel> selectedRequesterDegrees { get; set; }
}
View:
#model Test
#Html.DropDownListFor(x => x.selectedRequesterDegrees, new SelectList(Model.selectedRequesterDegrees, "Id", "Name"), null, new { id = "degreemultiselect", #class = "form-control" })
Controller:
[HttpGet]
public ActionResult Index()
{
var model = new Test()
{
selectedRequesterDegrees = new List<DegreeModel>()
{
new DegreeModel(){ Id=1,Name="aa"},
new DegreeModel(){ Id=2,Name="bb"},
new DegreeModel(){ Id=3,Name="cc"}
}
};
return View(model);
}
Result:
I don't know why it don't save the AddressBookId form a select in my database
public class CreditCard
{
public int Id { get; set; }
[Display (Name="Customer")]
public int CustomerID { get; set; }
[Display(Name = "Billing Address")]
public int AddressBooKId { get; set; }
public virtual Customer Customer { get; set; }
}
Controller:
public ActionResult Create()
{
ViewBag.CustomerID = new SelectList(db.Customers, "Id", "FullName");
ViewBag.CCTypeId = new SelectList(db.CreditCardTypes, "Id", "CCName");
return View();
}
public JsonResult AddList(int Id)
{
var add = from a in db.AddressBooks
where a.CustomerId== Id
select a;
return Json(new SelectList(add.ToArray(), "AddressBookId", "Address"), JsonRequestBehavior.AllowGet);
}
public IList<AddressBook> Getadd(int CustomeId)
{
return db.AddressBooks.Where(m => m.CustomerId== CustomeId).ToList();}
Mi view
<div class="form-group">
#Html.LabelFor(model => model.AddressBooKId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<select id="AddressBooKId" name="AddressBooKId" class="form-control"> </select><br />
#Html.ValidationMessageFor(model => model.AddressBooKId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
Json
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/jscript">
$(function () {
$('#AddressBooKId').html(null)
$('#CustomerID').change(function () {
$.getJSON('/CreditCards/AddList/' + $('#CustomerID').val(), function (data) {
var items = '<option>Select a Address</option>';
$.each(data, function (i, add) {
items += "<option value='" + add.Value + "'>" + add.Text + "</option>"; });
$('#AddressBooKId').html(items);
}); }); });
</script>
Because your Dropdown is not bound with Model. You are creating it as independent control.
<select id="AddressBooKId" name="AddressBooKId" class="form-control"> </select>
Change the list Id and name to "AddressBookList". Create hidden field to keep the AddressBookId using model.
#Html.HiddenFor(m => m.AddressBooKId);
Change your JS code to update the new dropdown name.
Create a new change event handler for AddressBookList and set the value of HiddenField.
$('#AddressBookList').change(function () {
$('#AddressBooKId').val($('#AddressBookList').val());
}
Now when form will be submitted the Model property AddressBookId will have the selected value.
I got a view with some textbox and a submit button
when i push submit i want the data of the textboxes in a json file(no database)
Now it works only for save 1data command when i psuh a second time on submit with other data
then hen rewrite my json file how can i save all of it ?
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
// jsonkalender.Add(new kalender() { Password = "" });
//kalender kl = new kalender();
//kl.Password = obj.Password;
//kl.MyEnum = TestEnum.taak;
//obj.Password = kl.Password;
//Load(null);
return View();
}
private const string JsonFileName1 = #"C:\\Users\Alexander\Desktop\times1.json";
private List<kalender> _times;
[HttpPost]
public ActionResult Index(kalender obj)
{
// Load(obj);
// _times.Add(new kalender() { Datum = DateTime.Now.ToString() });
kalender kl = new kalender();
Json(new { datum = obj.Datum,wachtwoord = obj.Password });
// _times.Add(obj);
try
{
}
catch (Exception) { }
obj.SelectedEnumId++;
// kl.Password = obj.Password;
var json = JsonConvert.SerializeObject(obj, Formatting.Indented);
using (var writer = new StreamWriter(JsonFileName1))
{
writer.Write(json);
}
return View();
}
private void Load(kalender obj)
{
if (System.IO.File.Exists(JsonFileName1))
{
using (var reader = new StreamReader(JsonFileName1))
{
var json = reader.ReadToEnd();
obj = JsonConvert.DeserializeObject<kalender>(json);
}
}
if (obj == null)
obj = new kalender();
}
}
}
Model
public class kalender
{
//public string Datum { get; set; }
// [Required]
// [DataType(DataType.Date)]
// public Nullable<System.DateTime> Datum { get; set; }
public string Datum { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string Type { get; set; }
[Required]
[Key]
public int SelectedEnumId { get; set; }
[Required]
public TestEnum MyEnum { get; set; }
}
}
View
#model PE1.Models.kalender
#{
ViewBag.Title = "Index";
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
}
#{
AjaxOptions options = new AjaxOptions();
options.HttpMethod = "POST";
options.Confirm = "Zeker?";
options.OnBegin = "OnBegin";
options.OnComplete = "OnComplete";
options.OnFailure = "OnFailure";
options.OnSuccess = "OnSuccess";
options.LoadingElementId = "divProgress";
options.LoadingElementDuration = 1000;
options.UpdateTargetId = "divResponse";
options.InsertionMode = InsertionMode.InsertAfter;
}
<script type="text/javascript">
$(function () { // will trigger when the document is ready
$('.datepicker').datepicker(); //Initialise any date pickers
});
</script>
<div>
<h1>Online Kalender</h1>
<div id="kader">
<p>THuis</p>
#using (Html.BeginForm("Index", "Home", options))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Kaldender</legend>
#*#Html.DropDownListFor(model => model.Password, listItems)*#<br />
#Html.LabelFor(model => model.Password)<br />
#Html.EditorFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)<br />
#Html.EnumDropDownListFor(model => model.MyEnum)
<div class="form-group input-group-sm">
#Html.LabelFor(model => model.Datum)
#Html.TextBoxFor(model => model.Datum, new { #class = "form-control datepicker", placeholder = "Enter Drop-off date here..." })
#Html.ValidationMessageFor(model => model.Datum)
</div>
<input type="submit" value="Submit"/>
<input type="reset" value="Reset"/>
</fieldset>
#Ajax.ActionLink("Klik hier om een Ajax ActionLink uit te voeren", "ProcessLink", options)
}
enum
public enum TestEnum : int
{
taak,
vergadering
}
my output is wrong how can i change it ?
{
"Datum": "10/28/2014",
"Password": "hrth",
"Type": null,
"SelectedEnumId": 0,
"MyEnum": 0,
"rand1": 0
}{
"Datum": "10/28/2014",
"Password": "hrth",
"Type": null,
"SelectedEnumId": 0,
"MyEnum": 0,
"rand1": 0
}
this is my json file but i need this
[
{
"Datum": "10/28/2014",
"Password": "hrth",
"Type": null,
"SelectedEnumId": 0,
"MyEnum": 0,
"rand1": 0
},{
"Datum": "10/28/2014",
"Password": "hrth",
"Type": null,
"SelectedEnumId": 0,
"MyEnum": 0,
"rand1": 0
}
]
Use the Overload for the SteamWriter object that appends to a file instead of overwriting a file.
http://msdn.microsoft.com/en-us/library/36b035cb(v=vs.110).aspx
using (var writer = new StreamWriter(JsonFileName1, true))
{
writer.Write(json);
}
Notice the addition of the bool true in the StreamWriter constructor
My Model:
namespace mvc4deneme.Models
{
public class SiparisModel
{
public string SelectedValue { get; set; }
public IEnumerable<SelectListItem> Values { get; set; }
[Display(Name = "Ürün Tipi")]
public Material UrunTipi { get; set; }
[Display(Name = "Yüzey")]
public Material Yuzey { get; set; }
public class Material
{
//public int? ID { get; set; }
public string ID { get; set; }
public string Name { get; set; }
}
}
MY CONTROLLER:
//my control page is SiparisController
public class SiparisController : Controller
{
//
// GET: /Siparis/
public ActionResult Index()
{
DataTable dt = null;
Material material = null;
var model = new SiparisModel();
List<Material> lstYuzey = new List<Material>{
new Material { ID = null, Name = "Seçiniz" },
new Material { ID = "D/-", Name = "Tek Yüz" },
new Material { ID = "D/D", Name = "Çift Yüz" } };
ViewBag.Yuzey = lstYuzey;
List<Material> lstUrunTipi = new List<Material> {
new Material { ID = null, Name = "Seçiniz" },
new Material { ID = "3100140", Name = "MKYL" },
new Material { ID = "3100180", Name = "FS.MKYL FA" },
new Material { ID = "3100190", Name = "FS.MKYL FC" },
new Material { ID = "3100090", Name = "YL" }, };
ViewBag.UrunTipi = lstUrunTipi;
return View(model);
}
}
MY Index.cshtml view page:
#using (Html.BeginForm())
{
#Html.DropDownListFor(x => x.SelectedValue, Model.Values)
<button type="submit">OK</button>
#Html.LabelFor(m => m.UrunTipi)
#Html.DropDownListFor(m => m.UrunTipi.ID,
new SelectList(ViewBag.UrunTipi, "ID", "Name"),
new { style = "width:310px" })
#Html.ValidationMessageFor(m => m.UrunTipi.ID) }
#using (Html.BeginForm())
{
#Html.LabelFor(m => m.Yuzey)
#Html.DropDownListFor(m => m.Yuzey.ID,
new SelectList( ViewBag.Yuzey,"ID", "Name"),
new { style = "width:310px" })
#Html.ValidationMessageFor(m => m.Yuzey.ID)
}
My Ask:
How can i execute ok button to getting values of my UrunTipi and Yuzey selected values.
Thank you so much.
Regards,
B.Y.