Why can't I convert List to Array? - c#

in my project I got an error I don't know why can't I convert a list to type system.array?
System.InvalidCastException: Unable to cast object of type
'System.Collections.Generic.List`1[DataLayer.Appoinment]' to type 'System.Array'.
public class User: IdentityUser
{
public User()
{
**//when I comment these codes my project is fired.**
this.Appoinments = new List<Appoinment>();
this.Offices = new List<Office>();
this.Schedules = new List<Schedule>();
this.Secretaries = new List<Secretary>();
}
public User(string userName) : base(userName)
{
}
[Display(Name = "نام")]
[MaxLength(250)]
[Required(ErrorMessage = " لطفآ {0} را وارد کنید")]
public string FirstName { get; set; }
[Display(Name = "نام خانوادگی")]
[MaxLength(250)]
[Required(ErrorMessage = " لطفآ {0} را وارد کنید")]
public string LastName { get; set; }
[Display(Name = "جنسیت")]
[Required(ErrorMessage = " لطفآ {0} را وارد کنید")]
public bool? Gender { get; set; }
[Display(Name = "تاریخ درج")]
public DateTime? CreateDate { get; set; }
[Display(Name = "تاریخ بروزرسانی")]
public DateTime? UpdateDate { get; set; }
[Display(Name = "وضعیت")]
public bool? IsActive { get; set; }
[MaxLength(500)]
[Display(Name = "آدرس")]
public string Address { get; set; }
[MaxLength(250)]
[Required(ErrorMessage = " لطفآ {0} را وارد کنید")]
[Display(Name = "شماره تماس")]
public virtual IList<Appoinment> Appoinments { get; set; }
public virtual IList<Office> Offices { get; set; }
public virtual IList<Schedule> Schedules { get; set; }
public virtual IList<Secretary> Secretaries { get; set; }
}
public class Appoinment
{
[Key]
public int AppointmentID { get; set; }
[MaxLength(300)]
public string TrakingCode { get; set; }
public DateTime? Shift { get; set; }
public bool? Status { get; set; }
public DateTime? Datepick { get; set; }
public DateTime? CreatedAt { get; set; }
public DateTime? UpdatedAt { get; set; }
public virtual User User { get; set; }
public virtual Schedule Schedule { get; set; }
}
==============================
#model DataLayer.User
#{
ViewBag.Title = "مدیریت کاربران";
}
#*<h2>افزودن کاربران</h2>*#
<br />
<div>
#Html.ActionLink("بازگشت به صفحه اصلی", "Index")
</div>
<!-- /.box -->
#using (Html.BeginForm("Create", "Users", FormMethod.Post))
{
#Html.AntiForgeryToken();
<div class="row">
<div class="col-md-8 col-lg-pull-2">
<div class="box box-danger">
<div class="box-header">
<h2 class="box-title">افزودن کاربران</h2>
</div>
<div class="box-body">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<label>نام</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-info"></i>
</div>
#Html.EditorFor(model => model.UserName, new { htmlAttributes = new { #class = "form-control", Type = "text", name = "Firstname", placeholder = "نام" } })
#Html.ValidationMessageFor(model => model.UserName, "", new { #class = "text-danger" })
#*<input type="text" class="form-control" placeholder="نام " name="FirstName">*#
</div>
<!-- /.input group -->
</div>
<div class="form-group">
<label>نام خانوادکی</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-info"></i>
</div>
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control", type = "text", name = "LastName", placeholder = "نام خانوادگی" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
<!-- /.input group -->
</div>
<!-- /.form group -->
<!-- phone mask -->
<div class="form-group">
<label>رمز عبور</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-key"></i>
</div>
#Html.EditorFor(model => model.PasswordHash, new { htmlAttributes = new { #class = "form-control", type = "password", name = "Password", placeholder = "...." } })
#Html.ValidationMessageFor(model => model.PasswordHash, "", new { #class = "text-danger" })
</div>
<!-- /.input group -->
</div>
<!-- /.form group -->
<!-- phone mask -->
<div class="form-group">
<label>ایمیل</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-envelope"></i>
</div>
<!-- /.input group -->
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control", type = "email", name = "Password", placeholder = "example#example.com" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
<!-- /.input group -->
</div>
<div class="row">
<div class="col-md-6">
<label>جنسیت</label>
<div class="form-group">
<div class="radio">
#Html.DropDownListFor(model => model.Gender,
new SelectListItem[] { new SelectListItem() { Text = "مرد", Value = "True" }, new SelectListItem() { Text = "زن", Value = "False" } }
, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Gender, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6">
<label>وضعیت</label>
<div class="form-group">
<div class="checkbox">
#Html.DropDownListFor(model => model.Gender,
new SelectListItem[] { new SelectListItem() { Text = "فعال", Value = "True" }, new SelectListItem() { Text = "غیرفعال", Value = "False" } }
, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Gender, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="form-group">
<label>شماره همراه</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-phone"></i>
</div>
#Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { #class = "form-control", type = "tel", name = "PhoneNumber", placeholder = "شماره همراه..." } })
#Html.ValidationMessageFor(model => model.PhoneNumber, "", new { #class = "text-danger" })
</div>
<!-- /.input group -->
</div>
<form role="form">
<!-- textarea -->
<div class="form-group">
<label>آدرس</label>
#Html.TextAreaFor(model => model.Address, new { #class = "form-control", type = "text", cols = "4", rows = "4", name = "Address", placeholder = "آدرس..." })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
#*<textarea class="form-control" rows="3" placeholder="آدرس ..."></textarea>*#
</div>
</form>
<!-- /.form group -->
<div class="row">
<div class="col-md-6">
<button type="button" class="btn btn-danger btn-flat btn-md"> انصراف</button>
<button type="submit" class="btn btn-success btn-flat btn-md"><span class="fa fa-plus"></span> افزودن کاربر جدید </button>
</div>
</div>
</div>
<!-- /.box-body -->
</div>
</div>
</div>
}

You're missing phone number property "شماره تماس" in the User class.

Related

I want to Add Property Type and Sub Types in RadioButton using MVC

I have Property Types and sub types that are stored in db, and i want to display these types and sub type in radiobutton.
I m sharing some details.
DB Tables Image
Here is ModelVM class
public class PropertyVM
{
//property table
public int property_id { get; set; }
public string property_purpose { get; set; }
public string property_sub_purpose { get; set; }
public string address { get; set; }
public string property_title { get; set; }
public string property_description { get; set; }
public Nullable<double> property_price { get; set; }
public Nullable<double> property_budget { get; set; }
public string property_land_area { get; set; }
public string bedroom { get; set; }
public string bathroom { get; set; }
public Nullable<int> property_status { get; set; }
public Nullable<System.DateTime> property_add_dateTime { get; set; }
public string property_ad_expiry { get; set; }
// property Type table
public int property_type_id { get; set; }
public string property_type_name { get; set; }
public Nullable<int> property_type_status { get; set; }
// property sub type table
public int property_sub_type_id { get; set; }
public string property_sub_type_name { get; set; }
public Nullable<int> property_sub_type_status { get; set; }
// for list of data
public string Selected_pt_list { get; set; }
public List<property_type> pt_list { get; set; }
public string Selected_pst_list { get; set; }
public List<property_sub_type> pst_list { get; set; }
}
Here is Controller Method
[HttpGet]
public ActionResult AddProperty()
{
PropertyVM obj = new PropertyVM();
obj.pt_list = db.property_type.Where(pt => pt.property_type_status == 1).ToList();
obj.pst_list = db.property_sub_type.Where(pst => pst.property_sub_type_status == 1).ToList();
return View(obj);
}
Here is UI Images
WHen Select 1st ProertyType(Radiobutton) it shows all its child subTYpes
WHen Select 2nd ProertyType(Radiobutton) it shows all its child subTYpes
WHen Select 3rd ProertyType(Radiobutton) it shows all its child subTYpes
NOTE : ALL PROPERTY TYPES AND SUB TYPES IN RADIO BUTTON, NOT CHECKBOX
Solve this issue by using Partialview Approach and Jquery and ajax.
Here is Solution
PartialView Property_Sub_Type
#model projectName.Areas.Dashboard.Models.ViewModels.PropertyVM
#foreach (var _pst in Model.pst_list)
{
//string divMainId = "propertyType" + _pst.property_type.property_type_name.Replace(" ", "") + "IfSelect";
string forLblSub = "radioPropertyType" + _pst.property_sub_type_name.Replace(" ", ""); // for label and its must use
forLblSub = forLblSub + _pst.property_sub_type_name.Replace(" ", ""); // for label and its must use
<div class="funkyradio">
<div class="funkyradio-info">
#Html.RadioButtonFor(ms => ms.Selected_pst_list, _pst.property_sub_type_id, new { #Name = "radioPropertyType" + _pst.property_sub_type_name.Replace(" ", "") + "Sub", id = "radioPropertyType" + _pst.property_type.property_type_name.Replace(" ", "") + _pst.property_sub_type_name.Replace(" ", "") })
<label for="#forLblSub">#_pst.property_sub_type_name</label>
</div>
</div>
}
Here is Main View Add_Property
#model ProjectName.Areas.Dashboard.Models.ViewModels.PropertyVM
#{
ViewBag.Title = "Add Property";
}
<!-- /.col -->
<div class="col-md-9">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Add a Property</h3>
#*#Html.Partial("~/Areas/Admin/Views/Shared/_errorMsg.cshtml")*#
</div>
<!-- /.box-header -->
<!-- form start -->
#using (Html.BeginForm("AddProperty", "PropertyManagment", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="box-body">
<div class="row heading_addProperty_main">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<span class="heading_addProperty_span">Property Purpose & Category</span>
</div>
</div>
<div class="form-group col-lg-12 col-md-12 col-sm-12" style="padding-left:0px;padding-right:0px;">
<label for="LabelPurpose" class="text-uppercase">Purpose</label>
<div class="funkyradio">
<div class="funkyradio-info">
#Html.RadioButtonFor(m => m.property_purpose, "Sale", new { #Name = "radioPurpose", id = "radioPurposeSale" })
<label for="radioPurposeSale">For Sale</label>
</div>
<div class="funkyradio-info">
#Html.RadioButtonFor(m => m.property_purpose, "Rent", new { #Name = "radioPurpose", id = "radioPurposeRent" })
<label for="radioPurposeRent">Rent</label>
</div>
<div class="funkyradio-info">
#Html.RadioButtonFor(m => m.property_purpose, "Wanted", new { #Name = "radioPurpose", id = "radioPurposeWanted" })
<label for="radioPurposeWanted">Wanted</label>
</div>
</div>
</div>
<!-- Wanted Sub Radio -->
<div class="form-group col-lg-12 col-md-12 col-sm-12" style="padding-left:10px;padding-right:0px;" id="wantedIfSelect">
<label for="LabelWanted" class="text-uppercase">Wanted</label>
<div class="funkyradio">
<div class="funkyradio-info">
#Html.RadioButtonFor(m => m.property_purpose, "Buy", new { #Name = "radioWanted", id = "radioWantedBuy" })
<label for="radioWantedBuy">Buy</label>
</div>
<div class="funkyradio-info">
#Html.RadioButtonFor(m => m.property_purpose, "Rent", new { #Name = "radioWanted", id = "radioWantedRent" })
<label for="radioWantedRent">Rent</label>
</div>
</div>
</div>
<!-- Property Type Partial View -->
#{Html.RenderAction("_PropertyTypePartial", "PropertyManagment");}
<!-- Property Type Partial View -->
<div class="form-group col-lg-12 col-md-12 col-sm-12" style="padding-left:10px;padding-right:0px;" id="loadPartial">
</div>
#*#{Html.RenderAction("_PropertySubTypePartial", "PropertyManagment", new { id = Model.Selected_pt_list });}*#
<div class="row heading_addProperty_main">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<span class="heading_addProperty_span">Property Location</span>
</div>
</div>
<div class="form-group col-lg-6 col-md-6 col-sm-6" style="padding-left:0px;">
<label for="LabelCity" class="text-uppercase">City</label>
#Html.DropDownList("city_id", null, "Select One", htmlAttributes: new { #class = "form-control select2" })
#Html.ValidationMessageFor(model => model.city_id, "", new { #class = "text-danger" })
</div>
<div class="form-group col-lg-6 col-md-6 col-sm-6" style="padding-right:0px;">
<label for="LabelLocation" class="text-uppercase">Address</label>
#Html.EditorFor(model => model.address, new { htmlAttributes = new { #class = "form-control", #PlaceHolder = "Enter Complete Address" } })
#Html.ValidationMessageFor(model => model.address, "", new { #class = "text-danger" })
</div>
<div class="row heading_addProperty_main">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<span class="heading_addProperty_span">Property Details</span>
</div>
</div>
<div class="form-group col-lg-6 col-md-6 col-sm-6" style="padding-left:0px;">
<label for="LabelPropertyTitle" class="text-uppercase">Property Title</label>
#Html.EditorFor(model => model.property_title, new { htmlAttributes = new { #class = "form-control", #PlaceHolder = "Enter Title" } })
#Html.ValidationMessageFor(model => model.property_title, "", new { #class = "text-danger" })
</div>
<div class="form-group col-lg-6 col-md-6 col-sm-6" style="padding-right:0px;">
<label for="LabelPrice" class="text-uppercase">Final Price (PKR)</label>
#Html.EditorFor(model => model.property_price, new { htmlAttributes = new { #class = "form-control", #PlaceHolder = "Enter Price (All Inclusive)" } })
#Html.ValidationMessageFor(model => model.property_price, "", new { #class = "text-danger" })
</div>
<div class="form-group col-lg-6 col-md-6 col-sm-6" style="padding-left:0px;">
<label for="LabelLandArea" class="text-uppercase">Land Area</label>
#Html.EditorFor(model => model.property_land_area, new { htmlAttributes = new { #class = "form-control", #PlaceHolder = "Enter Land Area" } })
#Html.ValidationMessageFor(model => model.property_land_area, "", new { #class = "text-danger" })
</div>
<div class="form-group col-lg-6 col-md-6 col-sm-6" style="padding-right:0px;">
<label for="LabelAreaUnit" class="text-uppercase">Area Unit</label>
#Html.DropDownList("land_area_unit_id", null, "Select One", htmlAttributes: new { #class = "form-control select2" })
#Html.ValidationMessageFor(model => model.land_area_unit_id, "", new { #class = "text-danger" })
</div>
<div class="form-group col-lg-6 col-md-6 col-sm-6" style="padding-left:0px;">
<label for="LabelDescription" class="text-uppercase">Description</label>
#Html.TextAreaFor(model => model.property_description, new { #class = "form-control", #cols = 3, #rows = 3, #style = " resize: none;" })
</div>
<div class="form-group col-lg-6 col-md-6 col-sm-6" style="padding-right:0px;">
<label for="LabelExpiresAfter" class="text-uppercase">Expires After</label>
<input type="text" class="form-control" placeholder="">
</div>
<div class="row heading_addProperty_main">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<span class="heading_addProperty_span">Add Images</span>
</div>
</div>
<div class="form-group col-lg-12 col-md-12 col-sm-12" style="padding-right:0px;padding-left:0px;">
<div class="upload-btn-wrapper">
<button class="btn_upload"><i class="icon icon-bar"></i> Upload Images</button>
<input type="file" name="propertyImages" multiple />
<span class="label label-warning" style="padding:5px; font-size:12px;"><i class=""></i> Press CTRL key while selecting images to upload multiple images at once</span>
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<input type="submit" class="btn btn-success btn-sm" value="Submit">
#Html.ActionLink("Back to List", "Index", "City", null, new { #class = "btn btn-primary btn-sm" })
</div>
}
</div>
</div>
<!-- /.col -->
Here is Jquery
// Load property sub type based on property type selection
$("input:radio[name='radioPropertyType']").change(function () {
// get selected radiobutton value
var id = $("input:radio[name='radioPropertyType']:checked").val();
// get div name where we display data
var divToLoad = $("#loadPartial");
// call controller method
$.ajax({
cache: false,
type: "GET",
url: "#(Url.Action("_PropertySubTypePartial", "PropertyManagment"))",
data: { "id": id },
success: function (data) {
divToLoad.html(' ');
divToLoad.html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
divToLoad.html(' ');
}
});
});

Validation of the form with Ajax request

I am trying to validate the input field form. Achieved some results. I use Ajax request.
Model:
public int Id { get; set; }
[Required]
[Display(Name = "Фамилия")]
public string CSurname { get; set; }
[Required]
[Display(Name = "Имя")]
public string CName { get; set; }
[Required]
[Display(Name = "Отчество")]
public string CPatronymic { get; set; }
[Required]
[Display(Name = "Логин")]
public string Login { get; set; }
[Required]
[Display(Name = "Пароль")]
public string Password { get; set; }
[Required]
[Display(Name = "E-meil")]
public string Email { get; set; }
public virtual ICollection<Order> Orders { get; set; }
public Client()
{
Orders = new List<Order>();
}
Controller:
[HttpPost]
public ActionResult Registration(Client client)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
return View();
}
View:
#using (Ajax.BeginForm("Registration", new AjaxOptions { UpdateTargetId = "results" }))
{
<div class="container">
<div class="form-signin">
<div class="form-group">
#Html.LabelFor(i => i.CSurname, "Фамилия")
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-text"><i class="fa fa-id-badge" aria-hidden="true"></i></span>
#Html.EditorFor(i => i.CSurname, new { htmlAttributes = new { #id = "txtSurname", #class = "form-control", #placeholder = "Введите фамилию" } })
</div>
#Html.ValidationMessageFor(i => i.CSurname, "", new { #class = "text-danger", #id = "mess" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(i => i.CName, "Имя")
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-text"><i class="fa fa-id-badge" aria-hidden="true"></i></span>
#Html.EditorFor(i => i.CName, new { htmlAttributes = new { #id = "txtName", #class = "form-control", #placeholder = "Введите имя" } })
</div>
#Html.ValidationMessageFor(i => i.CName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(i => i.CPatronymic, "Отчество")
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-text"><i class="fa fa-id-badge" aria-hidden="true"></i></span>
#Html.EditorFor(i => i.CPatronymic, new { htmlAttributes = new { #id = "txtPatr", #class = "form-control", #placeholder = "Введите отчество" } })
</div>
#Html.ValidationMessageFor(i => i.CPatronymic, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(i => i.Login, "Логин")
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-text"><i class="fa fa-user fa" aria-hidden="true"></i></span>
#Html.EditorFor(i => i.Login, new { htmlAttributes = new { #id = "txtLogin", #class = "form-control", #placeholder = "Введите логин" } })
</div>
#Html.ValidationMessageFor(i => i.Login, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(i => i.Password, "Пароль")
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-text"><i class="fa fa-lock fa" aria-hidden="true"></i></span>
#Html.PasswordFor(i => i.Password, new { #id = "txtPass", #class = "form-control", #placeholder = "Введите пароль" })
</div>
#Html.ValidationMessageFor(i => i.Password, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(i => i.Email, "E-Mail")
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-text"><i class="fa fa-envelope fa" aria-hidden="true"></i></span>
#Html.EditorFor(i => i.Email, new { htmlAttributes = new { #id = "txtMail", #class = "form-control", #placeholder = "Введите e-mail", #type = "email" } })
</div>
#Html.ValidationMessageFor(i => i.Email, "", new { #class = "text-danger" })
</div>
</div>
<input id="btnAdd" type="submit" class="btn btn-success btn-block" value="Добавить" />
</div>
</div>
}
Also the scripts are connected to the layout.
#Scripts.Render("~/scripts/jquery.validate.min.js")
#Scripts.Render("~/scripts/jquery.validate.unobtrusive.min.js")
There is an email type field.
As soon as I start to enter data into it, if you do not enter # then the message immediately pops out:
But, if i use Ajax.Beginform without connection
#Scripts.Render("~/scripts/jquery.validate.min.js")
#Scripts.Render("~/scripts/jquery.validate.unobtrusive.min.js")
When you click add, сlimbs another message in a different style.
This text contained in:
$('#txtMail')[0].validationMessage
How to me to achieve that when using Ajax of the request the same message?

How to add validation Rule for dynamically created multiple input in ASP.net?

Account Model Class:
[Table("Accounts")]
public class Account
{
public int Id { get; set; }
public string CompanyName { get; set; }
public float Interval { get; set; }
}
Mobile Model Class:
public class Mobile
{
public int Id { get; set; }
public string MobileNo { get; set; }
public virtual Account Account { get; set; }
public static Mobile Add(string mobile)
{
Mobile mobiles = new Mobile();
mobiles.MobileNo = mobile;
return mobiles;
}
}
Thus an account can have multiple mobile numbers. Now I create a form where multiple mobile numbers can be inserted:
#model PowerSupply.Models.CompanyAccountViewModel
#{
ViewBag.Title = "Register";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h3>Register</h3> <br />
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group row">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "col-sm-2 col-md-1 col-form-label" })
<div class="col-sm-10 col-md-3">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group row">
#Html.LabelFor(model => model.Interval, htmlAttributes: new { #class = "col-sm-2 col-md-1 col-form-label" })
<div class="col-sm-10 col-md-3">
#Html.EditorFor(model => model.Interval, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Interval, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group row">
#Html.LabelFor(model => model.Mobile, htmlAttributes: new { #class = "col-sm-2 col-md-1 col-form-label" })
<div class="col-sm-10 col-md-3">
<span class="add-new-icon glyphicon glyphicon-plus-sign" id="add_mobile"> </span>
<input name="Mobile" class="form-control" id="mobile_no" />
</div>
</div>
<div class="form-group row new_mobile_wrapper">
<div class="col-md-offset-3">
<div class="new_mobile_container">
</div>
</div>
</div>
<div class="form-group row">
<div class="col-md-offset-2 col-sm-10 col-md-2">
<input type="submit" value="Register" class="btn btn-primary col-sm-offset-1" />
</div>
</div>
}
the form look likes:
And Finally I set validation as follows:
public CompanyAccountViewModel Handle(CompanyAccountRegistrationResponseMessage message, CompanyAccountViewModel viewModel, ModelStateDictionary modelState)
{
if(!message.ValidationResult.IsValid)
{
foreach(var error in message.ValidationResult.Errors)
{
switch (error.PropertyName)
{
case "CompanyName":
modelState.AddModelError("Name",error.ErrorMessage);
break;
case "Interval":
modelState.AddModelError("Interval",error.ErrorMessage);
break;
}
}
}
return viewModel;
}
public class CompanyAccountRegistrationRequestMessageValidator : AbstractValidator<CompanyAccountRegistrationRequestMessage>
{
public CompanyAccountRegistrationRequestMessageValidator()
{
RuleFor(x=>x.CompanyName).NotEmpty().WithMessage("Please specify a Company Name");
RuleFor(x=>x.Interval).ExclusiveBetween(0,10).WithMessage("Interval value must be between 1 and 9");
}
}
This two validation Rules works perfectly. I want to apply validation to Mobile too, ie: mobile number should be unique. How can I do this?
Modification:
public class CompanyAccountViewModel
{
public string Name { get; set; }
public float Interval { get; set; }
public List<string> Mobile { get; set; }
}

Values lost when sent to controller

I want to send my EmailFormModel, which contains the Ressurs-list, to the controller where i want to do stuff with it. However I'm never able to access the values in my EmailFormModel in my controller. I tried to overcome this problem by using Sessions, but still it doesnt work.
The list Ressurs contains several Ressursbehov, but there is never more than one EmailFormModel.
My controller
namespace WebApplication6.Controllers
{
public class AppController : Controller
{
const string SESSION_SAVED_MODEL = "savedModel";
[HttpGet]
public ActionResult Index()
{
Session[SESSION_SAVED_MODEL] = new EmailFormModel();
return View(Session[SESSION_SAVED_MODEL]);
}
public ActionResult Sent()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(EmailFormModel model)
{
//other irrelevant code
if (Request.Params["Ekstra_Ressurs"] != null)
{
model.Ressurs.Add(new RessursBehov());
Session[SESSION_SAVED_MODEL] = model;
}
}
return View(model);
}
}
My model
namespace WebApplication6.Models
{
public class EmailFormModel
{
[Required, Display(Name = "Prosjektnummer")]
public string Prosjektnummer { get; set; }
[Required, Display(Name = "Prosjektnavn")]
public string Prosjektnavn { get; set; }
[Required, Display(Name = "Prosjekttype")]
public string Prosjekttype { get; set; }
[Required, Display(Name = "Prosjektleder")]
public string Prosjektleder { get; set; }
public List<RessursBehov> Ressurs = new List<RessursBehov>()
{
new RessursBehov() };
}
public class RessursBehov
{
[Required, Display(Name = "Ressurstype")]
public string Ressurstype { get; set; }
[Required, Display(Name = "Navn på ressurs")]
public string Navn_På_Ressurs { get; set; }
[Required, Display(Name = "Ukenummer")]
public int? Ukenummer { get; set; }
[Required, Display(Name = "Antall timer")]
public int? Antall_Timer { get; set; }
[Required, Display(Name = "Antall uker")]
public int? Antall_Uker { get; set; }
}
}
}
My View
#model WebApplication6.Models.EmailFormModel
#{
ViewBag.Title = "Registrer nytt prosjekt";
List<SelectListItem> prosjektTypeListe = new List<SelectListItem>()
{
new SelectListItem { Text = "Prosjekt", Value = "Prosjekt" },
new SelectListItem { Text = "Forvaltning", Value = "Forvaltning" }
};
List<SelectListItem> ressurstypeliste = new List<SelectListItem>()
{
new SelectListItem { Text = "utvikler", Value = "utvikler" },
new SelectListItem { Text = "frontendutvikler", Value = "frontendutvikler" },
new SelectListItem { Text = "epi-utvikler", Value = "epi-utvikler" },
new SelectListItem { Text = "webnodesutvikler", Value = "webnodesutvikler" },
new SelectListItem { Text = "designer", Value = "designer" },
new SelectListItem { Text = "rådgiver", Value = "rådgiver" },
new SelectListItem { Text = "prosjektleder", Value = "prosjektleder" }
};
}
<div class="title">
<div class="text-center">
<h2>#ViewBag.Title</h2>
</div>
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="rows">
<div class="row">
<div class="col-md-4"></div>
#Html.LabelFor(m => m.Prosjektnummer, new { #class = "col-md-1 text-center" })
<div class="col-md-7">
#Html.TextBoxFor(m => m.Prosjektnummer, new { #class = "html_label" })
#Html.ValidationMessageFor(m => m.Prosjektnummer)
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
#Html.LabelFor(m => m.Prosjektnavn, new { #class = "col-md-1 text-center" })
<div class="col-md-7">
#Html.TextBoxFor(m => m.Prosjektnavn, new { #class = "html_label" })
#Html.ValidationMessageFor(m => m.Prosjektnavn)
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
#Html.LabelFor(m => m.Prosjekttype, new { #class = "col-md-1 text-center" })
<div class="col-md-7">
#Html.DropDownListFor(m => m.Prosjekttype, prosjektTypeListe, "-- Velg Prosjekttype --", new { #class = "dropdown" })
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
#Html.LabelFor(m => m.Prosjektleder, new { #class = "col-md-1 text-center" }) <!--tar inn m som parameter og returnerer m.prosjektleder-->
<div class="col-md-7">
#Html.TextBoxFor(m => m.Prosjektleder, new { #class = "html_label" })
#Html.ValidationMessageFor(m => m.Prosjektleder)
</div>
</div>
#for (var i = 0; i < Model.Ressurs.Count; i++)
{
<div class="row">
<div class="col-md-4"></div>
#Html.LabelFor(m => Model.Ressurs[i].Ressurstype, new { #class = "col-md-1 text-center" })
<div class="col-md-7">
#Html.DropDownListFor(m => Model.Ressurs[i].Ressurstype, ressurstypeliste, "-- Velg ressurstype --", new { #class = "dropdown" })
</div>
</div>
<div class="row">
<div class="col-md-3"></div>
#Html.LabelFor(m => Model.Ressurs[i].Navn_På_Ressurs, new { #class = "col-md-2 text-right" })
<div class="col-md-7">
#Html.TextBoxFor(m => Model.Ressurs[i].Navn_På_Ressurs, new { #class = "html_label" })
#Html.ValidationMessageFor(m => Model.Ressurs[i].Navn_På_Ressurs)
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
#Html.LabelFor(m => Model.Ressurs[i].Ukenummer, new { #class = "col-md-1 text-center" })
<div class="col-md-7">
#Html.TextBoxFor(m => Model.Ressurs[i].Ukenummer, new { #class = "html_label" })
#Html.ValidationMessageFor(m => Model.Ressurs[i].Ukenummer)
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
#Html.LabelFor(m => Model.Ressurs[i].Antall_Timer, new { #class = "col-md-1 text-center" })
<div class="col-md-7">
#Html.TextBoxFor(m => Model.Ressurs[i].Antall_Timer, new { #class = "html_label" })
#Html.ValidationMessageFor(m => Model.Ressurs[i].Antall_Timer)
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
#Html.LabelFor(m => Model.Ressurs[i].Antall_Uker, new { #class = "col-md-1 text-center" })
<div class="col-md-7">
#Html.TextBoxFor(m => Model.Ressurs[i].Antall_Uker, new { #class = "html_label" })
#Html.ValidationMessageFor(m => Model.Ressurs[i].Antall_Uker)
</div>
</div>
}
<br />
<div class="row">
<div class="col-md-5"></div>
<div class="col-md-2">
<input type="submit" class="btn btn-default" value="Legg til ressurser" name="Ekstra_Ressurs" />
</div>
<div class="col-md-2">
<input type="submit" class="btn btn-primary" value="Send inn mail" name="Sendknapp" />
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
In order to reach model in HttpPost Index action
1) You should pass EmailFormModel type model to View in the GET Index action method.
EmailFormModel model = new EmailFormModel();
Session[SESSION_SAVED_MODEL]=model;
return View(model);
2) You should use Model at the lambda expressions
#Html.TextBoxFor(m => Model.Prosjektleder, new { #class = "html_label" })
change all ms with Model.
All you have to do is add #Name in html attribute then you wont need to use session also .
#Html.DropDownListFor(m => m.Prosjekttype, prosjektTypeListe , "-- Velg Prosjekttype --", new { #class = "dropdown" , #Name = "Prosjekttype" })

MVC 5 Razor - Label isn't updated from class annotation

I have a simple example.
Two class. User and Company like :
public class User() {
public int UserID { get; set; }
[Display(Name = "User name")]
public string Name { get; set; }
[Display(Name = "Company")]
public int CompanyID { get; set; }
public virtual Company Company { get; set; }
}
public class Company() {
public int CompanyID { get; set; }
[Display(Name = "Company")]
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
My problem is in the Create and the Edit views of the User.
The label for "Name" is displayed correctly in "User name" but the label for "CompanyID" stay displayed at "CompanyID" (the drop down list is created correctly with all Companies). I want the label display "Company" like I make it in the class.
I've try to change my view but all I do block compilation so I'm lost.
I'm begginer in MVC so excuse me if it easy to do but I don't see it.
Edit (add Create View code) :
#model Intranet3.Models.User
#{
ViewBag.Title = "Add a user";
}
#using (Html.BeginForm(null, null, FormMethod.Post, htmlAttributes: new { #class = "form-horizontal form-bordered" })) {
#Html.AntiForgeryToken()
<div class="row-fluid">
<div class="span12">
<div class="box">
<div class="box-title">
<h3>
<i class="icon-table"></i>
New
</h3>
</div>
<div class="box-content nopadding">
<div class="form-horizontal">
#Html.MyValidationSummary()
<div class="control-group #Html.ClassErrorFor(model => model.Name)">
#Html.LabelFor(model => model.Name, new { #class = "control-label" })
<div class="controls">
#Html.EditorFor(model => model.Name)
#Html.MyValidationMessageFor(model => model.Name)
</div>
</div>
<div class="control-group #Html.ClassErrorFor(model => model.CompanyID)">
#Html.LabelFor(model => model.CompanyID, "CompanyID", new { #class = "control-label" })
<div class="controls">
#Html.DropDownList("CompanyID", String.Empty)
#Html.MyValidationMessageFor(model => model.CompanyID)
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Create</button>
<button onclick="location.href='#Url.Action("Index","User")'" type="button" class="btn">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</div>
}
Edit 2 :
Problem solved by delete the string force in Labels.
So this :
#Html.LabelFor(model => model.CompanyID, "CompanyID", new { #class = "control-label" })
Need to be
#Html.LabelFor(model => model.CompanyID, new { #class = "control-label" })
Why have u passed parameter CompanyId
#Html.LabelFor(model => model.CompanyID, "CompanyID", new { #class = "control-label" })
Should be
#Html.LabelFor(model => model.CompanyID, new { #class = "control-label" })
#Html.TextBoxFor(c => c.CompanyID, new { data_bind = "text:Contacts.FirstName", #class = "form-control" })
If you have knockoutjs binding

Categories