Validation of the form with Ajax request - c#

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?

Related

ASP.NET core all model values are null when passing a model to the view

Goal: I have a page that I want to have a return url passed through the model of the view so upon completion of the form, it will return to the previous url. The page is a address validation and add it to the account as a saved address.
Flow of the page: You are presented with an address form to fill out. on completion, you will have a button that will call to a controller method that will verify with FedEx via API, and then if valid, it will let you save the address.
Issue: once you press the Verify Address button, it seems to have an issue with sending the form data to the controller.
HTTPGET:
public ActionResult AddShippingAddress(string strReturnURL)
{
// get states
ViewBag.states = GetStates();
DeliveryAddressModel model = new DeliveryAddressModel();
model.strReturnAddress = strReturnURL;
return View(model);
}
AddShippingAddress.chshtml
#model EcommerceWebsite.Models.Home.DeliveryAddressModel
#{
ViewBag.Title = "Shipping Address";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<div class="container">
<partial id="ValidateAddress"></partial>
#using (Html.BeginForm())
{
<h4>Shipping Address</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<h5>Name</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Attention To</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strAttnTo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strAttnTo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Street</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strStreet1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strStreet1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Street 2</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strStreet2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strStreet2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>City</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strCity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strCity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#{
IEnumerable<SelectListItem> dataItems = ViewBag.states;
}
<div class="form-group">
<h5>State</h5>
<div class="col-md-10">
#Html.DropDownListFor(model => model.State.IntStateId, dataItems, "-- Select --", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.State.IntStateId, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<h5>Zip</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strZip, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strZip, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Phone Number</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strPhoneNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strPhoneNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Set as Default</h5>
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.blnIsDefault)
#Html.ValidationMessageFor(model => model.blnIsDefault, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" class="btn btn-primary" data-ajax-method="get" data-toggle="ajax-modal"
data-url="#Url.Action("GetValidationOnAddress", new { model = Model })">
Verify Address
</button>
</div>
</div>
}
</div>
<script>
$(function () {
var PlaceHolderElement = $('#ValidateAddress');
$('button[data-toggle="ajax-modal"]').click(function (event) {
event.preventDefault();
var url = $(this).data('url');
// get the form containing the submit button
var form = $(this).closest('form')
// serialize all the fields in the form
var model = form.serialize();
// the the request to the url along with the form (model) data
$.get(url, model).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
//$('#ValidateAddress').modal('show');
})
})
})
</script>
Here is the partial:
#model EcommerceWebsite.Models.Home.DeliveryAddressModel
<div class="modal fade" id="ValidateAddress">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="ValidateAddressLabel">Validate Address</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#using (Html.BeginForm("AddShippingAddressToUser", "Home"))
{
#Html.HiddenFor(x => x.strName)
#Html.HiddenFor(x => x.strAttnTo)
#Html.HiddenFor(x => x.strStreet1)
#Html.HiddenFor(x => x.strStreet2)
#Html.HiddenFor(x => x.strCity)
#Html.HiddenFor(x => x.State.StrStateCode)
#Html.HiddenFor(x => x.State.StrStateName)
#Html.HiddenFor(x => x.State.IntStateId)
#Html.HiddenFor(x => x.strZip)
#Html.HiddenFor(x => x.strPhoneNumber)
#Html.HiddenFor(x => x.blnIsDefault)
<div class="modal-body">
<form action="Create">
<div class="form-group">
#if (Model.ErrorMessage == null)
{
<h5>#Model.strName</h5>
#if (Model.strAttnTo != null)
{<h5>#Model.strAttnTo</h5>}
<h5>#Model.strStreet1</h5>
#if (Model.strStreet2 != null)
{<h5>#Model.strStreet2</h5>}
<h5>#Model.strCity</h5>
<h5>#Model.State.StrStateCode</h5>
<h5>#Model.strZip</h5>
<h5>#Model.strPhoneNumber</h5>
<div class="modal-footer">
<button type="submit" value="Save" class="btn btn-primary">Save</button>
<button type="button" value="Edit" class="btn btn-secondary" data-dismiss="modal">Edit</button>
</div>
}
else
{
<h4>#Model.ErrorMessage</h4>
}
</div>
</form>
</div>
}
</div>
</div>
</div>
When all is said and done and the get validation button is pressed, it's supposed to send all the data to the controller and Verify the address with FedEx. But everything is null..
Now something to note, when I change the return of the httpget to return View(); everything works except it doesn't send the URL.
Update:
The AddShippingAddressToUser() hasn't even been called yet. The error lies somewhere in lines 101 - 102. Inside the button or the line 618 on the home controller.
Update: Here's the Model
public class DeliveryAddressModel
{
//[Required]
//[Display(Name = "First & Last Name")]
public string strName { get; set; }
//[Display(Name = "Attention To")]
public string strAttnTo { get; set; }
//[Required]
//[Display(Name = "Street 1")]
public string strStreet1 { get; set; }
//[Display(Name = "Street 2")]
public string strStreet2 { get; set; }
//[Required]
//[Display(Name = "City")]
public string strCity { get; set; }
//[Required]
//[Display(Name = "State")]
public Tstate State { get; set; }
//[Required]
//[Display(Name = "Zipcode")]
public string strZip { get; set; }
//[Required(ErrorMessage = "You must provide a phone number")]
//[Display(Name = "Phone Number")]
//[DataType(DataType.PhoneNumber)]
//[RegularExpression(#"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid phone number")]
public string strPhoneNumber { get; set; }
public bool blnIsDefault { get; set; }
public string ErrorMessage { get; set; }
public string strReturnAddress { get; set; }
}
First thing, since your form's function isnt a retrieval operation and a creational operation, use the http verb POST and not GET. Replace the HttpVerb filter above your action from HttpGet to HttpPost.
Second add this:
#using (Html.BeginForm("AddShippingAddressToUser", "Home", FormMethod.Post))
Alternatively,
#using (Html.BeginForm("AddShippingAddressToUser", "Home", FormMethod.Get))
Before your model in the action add: [FromQuery]

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(' ');
}
});
});

List<string> Property Mapping is not working

I have a List property (Mac) and I mapped it as follow:
View Model:
public class UserViewModel
{
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public virtual IList<string> Mac
{
get
{
return _Mac;
}
set
{
_Mac = value;
}
}
private IList<String> _Mac;
public string MacSerialized
{
get
{
return JsonConvert.SerializeObject(_Mac);
}
set
{
_Mac = JsonConvert.DeserializeObject<IList<string>>(value);
}
}
}
Razor View:
#model RouterManagement.Models.UserViewModel
#{
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.Email, htmlAttributes: new { #class = "col-sm-2 col-md-1 col-form-label" })
<div class="col-sm-10 col-md-3">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group row">
#Html.LabelFor(model => model.Mac, 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_mac"> </span>
#*Html.EditorFor(model => model.Mac, new { htmlAttributes = new { #class = "form-control", #id = "mac_addr" } })*#
#Html.EditorFor(model => model.MacSerialized, new { htmlAttributes = new { #class = "form-control", #id = "mac_addr" } })
#Html.ValidationMessageFor(model => model.MacSerialized, "", new { #class = "text-danger" })
<!-- <input name="Mac" class="form-control" id="mac_addr" /> -->
</div>
</div>
<div class="form-group row new_mac_wrapper">
<div class="col-md-offset-3">
<div class="new_mac_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>
}
And Action:
[HttpPost]
public ActionResult Register(UserViewModel model)
{
CancellationTokenSource cancelToken = new CancellationTokenSource();
AccountRegistrationRequestMessage requerstMessage = new AccountRegistrationRequestMessage();
requerstMessage.FullName = model.Name;
requerstMessage.EmailAddress = model.Email;
requerstMessage.MacAddresses = model.Mac;
requerstMessage.RegistrationType = AccountRegistrationEnum.IndividualAccountRegistration;
Task<AccountRegistrationResponseMessage> response = _interactor.Handle(requerstMessage, cancelToken.Token);
UserViewModel viewModel = _presenter.Handle(response.Result, model, ModelState);
if (response.Result.ValidationResult.IsValid)
{
//return View("DetailView", viewModel);
}
return View(viewModel);
}
When I submit data I am getting the following error:
Rendered form is look like:
Here, extra field of Mac is being created with jquery. Whats wrong in my approach? Don't address me bad as I am new in ASP.Net. Thanks for your time.

Why can't I convert List to Array?

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.

Creating a subform to upload update another entity

this is driving me mad because it seems like such a basic thing, and yet I cannot for the life of me google it out...
I have Two Models in the Portfolio Part of my MVC website
public class PortfolioEntry
{
public int ID { get; set; }
[Display(Name="Project Name")]
public string Name { get; set; }
[Display(Name="Created for")]
public string Client { get; set; }
public string Description { get; set; }
[Display(Name ="Started at")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime Start { get; set; }
[Display(Name ="Ended by")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime End { get; set; }
[Display(Name ="Skills used")]
public string Category { get; set; }
[Display(Name ="GitHub Link")]
public string GitHubLink { get; set; }
[Display(Name ="Solution Screenshots")]
public virtual ICollection<ScreenShot> ScreenShots { get; set; }
}
And the second one:
public enum ScreenShotType
{
[Display(Name = "Use case Diagram")]
UseCase,
[Display(Name = "Behaviour Diagram")]
Behavior,
[Display(Name ="Class Diagram")]
ClassStructure,
[Display(Name ="Main View")]
MainPage,
[Display(Name = "Additional View")]
SomthingCool
}
public class ScreenShot
{
public int ID { get; set; }
public string Description { get; set; }
[Display(Name="Screenshot Type")]
public ScreenShotType Type { get; set; }
public string ImageURL { get; set; }
public int Sorting { get; set; }
public int PortfolioEntryID { get; set; }
}
}
Now what I want to do is create a subform that allows me to on the fly Upload a ScreenShot and create a new record in the database for it (you click browse..., select the photo, fill in the info for it and click "Upload").
Then return the "Main" form so I can either upload another one or just save the whole thing altogether.
How should I go about it? I Tried creating a new action in the controller:
public async Task<ActionResult> UploadPhoto([Bind(Include = "ID,Name,Client,Description,Start,End,GitHubLink")] PortfolioEntry portfolioEntry, HttpPostedFileBase uploadedFile, string description, int sorting)
{
if (uploadedFile!=null && uploadedFile.ContentLength>0 && uploadedFile.ContentType.Contains("image"))
{
string extension = Path.GetExtension(uploadedFile.FileName.ToString().ToLower());
string fileName = "PorfolioImage" + String.Format("{0:D5}", db.Photos.Count()) + extension;
var path = Path.Combine(Server.MapPath("~/Pictures/ScreenShots"), fileName);
uploadedFile.SaveAs(path);
var screenshotToAdd = new ScreenShot
{
Description = description,
Sorting = sorting,
PortfolioEntryID = portfolioEntry.ID,
ImageURL = fileName
};
await db.SaveChangesAsync();
}
return(View(portfolioEntry));
}
But:
1. It does not see the uploaded file
2. Even if it did see the file it does not seem to register the Entity from the Bind
I've seen one solution by: mkozicki but before I re-write the methods I'd like to know if it is the path I should take.
Adam
EDIT: As per the follow up adding the View:
#model KoscielniakInfo.Models.PortfolioEntry
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>PortfolioEntry</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#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">
#Html.LabelFor(model => model.Client, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Client, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Start, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Start, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Start, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.End, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.End, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.End, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.GitHubLink, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.GitHubLink, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.GitHubLink, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-1 col-md-10">
<table>
<tr>
#{
int cnt = 0;
foreach (var category in ViewBag.Categories)
{
if (cnt++ % 3 == 0)
{
#Html.Raw("</tr><tr>")
}
#Html.Raw("<td>")
<input type="checkbox"
name="selectedCategories"
value="#category.Name"
#(Html.Raw(category.Selected ? "checked=\"checked\"" : "")) />
#category.Name
#Html.Raw("</td>")
}
#Html.Raw("</tr>")
}
</table>
</div>
</div>
<div class="form-group">
<div id="newCats" class="col-md-10 col-md-offset-1">
<div id="newCat">
<h5>
New Category
</h5>
<input type="text" name="newCategories" /><br />
</div>
</div>
<div class="col-md-10 col-md-offset-1">
<input id="clone" type="button" value="More Categories" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
#*=================================This is the form Group for adding the photo ============================================*#
<div class="form-group">
<div class="row">
<div class="col-md-offset-2 col-md-3">
Description:
</div>
<div class="col-md-7">
<input type="text" name="description" id="description" />
</div>
</div>
<div class="row">
<div class="col-md-offset-2 col-md-3">
screenType:
</div>
<div class="col-md-7">
<input type="text" name="screenType" />
</div>
</div>
<div class="row">
<div class="col-md-offset-2 col-md-3">
Sorting:
</div>
<div class="col-md-7">
<input type="number" name="sorting" id="sorting" />
</div>
</div>
<div class="row">
<div class="col-md-offset-2 col-md-3">
Image:
</div>
<div class="col-md-7">
<input type="file" name="uploadedFile" />
</div>
<input type="button" value="Create" onclick="location.href='#Url.Action("UploadPhoto", "PorfolioEntries")'" />
</div>
</div>
//=============================================Ends Here =========================================================================
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$('#clone').click(function () {
$('#newCat').last().clone().appendTo('#newCats')
})
</script>
}

Categories