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" })
Related
I am try to work on simple School management system using ASP .NET MVC 5 and SQL Server 2012 with database first approach.
The entity of student is related with an entity class, as every student would be enrolled in a class. SO have a 'Class' type variable and FK to the Classes table as attributes of my student entity.
Create View of Student has a dropdown list that shows the classes a student can be enrolled in. The dropdown is getting populated finely enough, but when the student is created and is viewed at the Index view, its class is NULL. When I checked the FK of created Students in Server Management studio, i found that the FK is being passed as NULL.
Can someone please let me know what I am doing wrong here.
PS. I am new to ASP .NET and I am not using a viewmodel because the tutorial I followed didn't and also because I didn't feel the need of making one.
Here is my Student.cs
using System;
using System.Collections.Generic;
public partial class Student
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Student()
{
this.Attendences = new HashSet<Attendence>();
}
public int St_id { get; set; }
public string St_name { get; set; }
public string St_guardian_name { get; set; }
public string St_guardian_relation { get; set; }
public string St_guardian_contact { get; set; }
public string St_address { get; set; }
public System.DateTime St_dob { get; set; }
public Nullable<int> St_cl_fk_id { get; set; }
public int St_status { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Attendence> Attendences { get; set; }
public virtual Class Class { get; set; }
}
Here is my Create Action in the StudentsController. PopulateClassDropDown is a helper method.
private void PopulateClassDropDownList(object selectedClass = null)
{
var classQuery = from c in db.Classes
where c.Cl_status==1
select c;
ViewBag.classID = new SelectList(classQuery, "Cl_id", "Cl_name", selectedClass);
}
[Authorize]
// GET: Students/Create
public ActionResult Create()
{
PopulateClassDropDownList();
return View();
}
// POST: Students/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "St_id,St_name,St_guardian_name,St_guardian_relation,St_guardian_contact,St_address,St_dob,St_cl_fk_id.St_status")] Student student)
{
try
{
var temp = student.St_cl_fk_id;
if (ModelState.IsValid)
{
student.St_status = 1;
db.Students.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (RetryLimitExceededException /* dex*/ )
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
PopulateClassDropDownList(student.St_cl_fk_id);
return View(student);
}
And finally here is the Create View of Student.
#model GMASchoolProject.Models.Student
#{
ViewBag.Title = "Create";
}
<link rel="stylesheet" type="text/css" href="~/Content/Site.css">
<div class="row" style="margin-bottom:5px;">
<div class="col-lg-12">
<h1 class="page-header">Create New Student</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="panel panel-default">
<div class="panel-heading">
Fill in Details
</div>
<div class="panel-body">
<div class="row">
<form class="col-lg-6" role="form">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group" style="margin:15px;">
#Html.LabelFor(model => model.St_name, "Student Name", htmlAttributes: new { #class = "control-label" })
<div>
#Html.EditorFor(model => model.St_name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.St_name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" style="margin:15px;">
#Html.LabelFor(model => model.St_guardian_name, "Name of Guardian", htmlAttributes: new { #class = "control-label " })
<div>
#Html.EditorFor(model => model.St_guardian_name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.St_guardian_name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" style="margin:15px;">
#Html.LabelFor(model => model.St_guardian_relation, "Guardian's Relation", htmlAttributes: new { #class = "control-label" })
<div>
#Html.DropDownListFor(model => model.St_guardian_relation, new[] {
new SelectListItem() {Text="Parents", Value="Parents" },
new SelectListItem() {Text="Other", Value="Other" }
},"Choose an option", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.St_guardian_relation, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" style="margin:15px;">
#Html.LabelFor(model => model.St_guardian_contact, "Guardian's Contact", htmlAttributes: new { #class = "control-label" })
<div>
#Html.EditorFor(model => model.St_guardian_contact, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.St_guardian_contact, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" style="margin:15px;">
#Html.LabelFor(model => model.St_address, "Student's Address", htmlAttributes: new { #class = "control-label" })
<div>
#Html.TextAreaFor(model=>model.St_address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.St_address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" style="margin:15px;">
#Html.LabelFor(model => model.St_dob, "Student's Date of Birth", htmlAttributes: new { #class = "control-label" })
<div>
#Html.EditorFor(model => model.St_dob, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.St_dob, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" style="margin:15px;">
<label class="control-label col-md-2" for="ClassID">Class</label>
<div>
#Html.DropDownList("classID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.St_cl_fk_id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" style="margin:15px,0,15px,0;">
<div class="col-md-offset-5 col-md-2">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index", null, new { #class = "btn btn-danger" })
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Based on this, make these changes:
// classId implies a scalar value, this should be a list
ViewBag.classList = new SelectList(classQuery, "Cl_id", "Cl_name", selectedClass);
// Change your dropdown code:
#Html.DropDownList("St_cl_fk_id", (SelectList)ViewBag.classList, htmlAttributes: new { #class = "form-control" })
// or better yet:
#Html.DropDownListFor(m => m.St_cl_fk_id, (SelectList)ViewBag.classList, new { #class = "form-control" })
// remove this line - it should bind automatically
var temp = student.St_cl_fk_id;
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?
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; }
}
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.
I have PROPERTY VM which contains List<FounderInvestmentViewModel>.I have successfully inserted the partial view of FounderInvestmentViewModel into the Main Create Property view.
FounderInvestmentViewModel in turn contains List<InstallmentDetailsViewModel>. I have created the Partial View for InstallmentDetailsViewModel as _InstallmentDetails.cshtml and all the necessary actions.
I want to insert the _InstallmentDetails.cshtml into the partial view of FounderInvestmentViewModel which is in turn inserted into the Main View.
First let us take a look at the codes that I have used so far :--
Property View Model:-
public class PropertyViewModel
{
public int? Id { get; set; }
public string PropertyTitle { get; set; }
....other attributes....
public List<FounderInvestmentViewModel> FounderInvestments { get; set; } = new List<FounderInvestmentViewModel>();
}
FounderInvestmentViewModel:-
public class FounderInvestmentViewModel
{
public int? Id { get; set; }
public int InvestorId { get; set; }
public double Investment { get; set; }
public int InstallmentPeriod { get; set; }
public IEnumerable<SelectListItem> FounderInvestorList { get; set; }
public List<InstallmentDetailsViewModel> InstallmentDetails { get; set; } = new List<InstallmentDetailsViewModel>();
}
InstallmentDetailsViewModel:-
public class InstallmentDetailsViewModel
{
public int? Id { get; set; }
[Display(Name = "Pay Date")]
public List<DateTime> PayDates { get; set; }
[Required]
public List<double> InstallmentAmounts { get; set; }
}
PartialView for InstallmentDetails (_InstallmentDetails.cshtml):-
#model propertyMgmt.ViewModel.InstallmentDetailsViewModel
<div class="installmentDetails">
#using (Html.BeginCollectionItem("InstallmentDetails"))
{
#Html.HiddenFor(m => m.Id, new { #class = "id" })
<div class="form-group">
#Html.LabelFor(m => m.InstallmentAmounts, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(m => m.InstallmentAmounts, new { htmlAttributes = new { #class = "form-control", #type = "number" } })
#Html.ValidationMessageFor(m => m.InstallmentAmounts, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.PayDates, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(m => m.PayDates, new { htmlAttributes = new { #class = "form-control", #placeholder = "01/02/2017" } })
#Html.ValidationMessageFor(m => m.PayDates, "", new { #class = "text-danger" })
</div>
</div>
}
</div>
This _InstallmentDetails.cshtml is inserted into this _FounderInvestmentDetails.cshtml which is PartialView for FounderInvestmentDetails View Model:-
#model propertyMgmt.ViewModel.FounderInvestmentViewModel
<div class="founderInvestmentDetails">
#using (Html.BeginCollectionItem("FounderInvestments"))
{
#Html.HiddenFor(m => m.Id, new { #class = "id" })
<div class="form-group">
#Html.LabelFor(m => m.InvestorId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.InvestorId, Model.FounderInvestorList, "Select Investor", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.InvestorId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Investment, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(m => m.Investment, new { htmlAttributes = new { #class = "form-control", #type = "number" } })
#Html.ValidationMessageFor(m => m.Investment, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.InstallmentPeriod, htmlAttributes: new { #class = "control-label col-md-2", #type = "number" })
<div class="col-md-10">
#Html.EditorFor(m => m.InstallmentPeriod, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(m => m.InstallmentPeriod, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" id="installmentDetailsDiv">
#foreach (var InstallmentDetails in Model.InstallmentDetails)
{
#Html.Partial("_InstallmentDetails", InstallmentDetails)
}
</div>
<div class="form-group col-md-10">
<input type="button" class="btn btn-info btn-xs" value="Add Installment Details" onclick="addInstallmentDetails()" />
</div>
}
</div>
This is the MAIN CREATE VIEW :-
#model propertyMgmt.ViewModel.PropertyViewModel.PropertyViewModel
#{
ViewBag.Title = "Create";
}
<script src="~/Areas/Admin/themes/jquery/jquery.min.js"></script>
<h2>Property</h2>
#using (Html.BeginForm("Create", "Property", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Add Property</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.PropertyTitle, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PropertyTitle, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PropertyTitle, "", new { #class = "text-danger" })
</div>
</div>
.....Other form Groups.....
<div id="founderInvestmentDetails">
#foreach(var FounderInvestments in Model.FounderInvestments)
{
#Html.Partial("_FounderInvestmentDetails", FounderInvestments)
}
</div>
<div class="form-group col-md-10" >
<input type="button" class="btn btn-info btn-xs" value="Add Founder Investors" onclick="addFounderInvestors()" />
</div>
</div>
}
This is My JS Code in the Main View:-
function addFounderInvestors() {
var url = '#Url.Action("FounderInvestmentDetails")';
var form = $('form');
var founders = $('#founderInvestmentDetails');
$.get(url, function (response) {
founders.append(response);
// Reparse the validator for client side validation
form.data('validator', null);
$.validator.unobtrusive.parse(form);
});
};
function addInstallmentDetails() {
var url = '#Url.Action("InstallmentDetails")';
var form = $('form');
var installments = $('#installmentDetailsDiv');
$.get(url, function (response) {
installments.append(response);
// Reparse the validator for client side validation
form.data('validator', null);
$.validator.unobtrusive.parse(form);
});
};
Controller Code :-
public PartialViewResult FounderInvestmentDetails()
{
var model = new FounderInvestmentViewModel {
FounderInvestorList = _investorQueryProcessor.GetInvestorByType(1).Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.InvestorName
})
};
//return PartialView(model);
return PartialView("_FounderInvestmentDetails", model);
}
public PartialViewResult InstallmentDetails()
{
return PartialView("_InstallmentDetails",new InstallmentDetailsViewModel());
}
public ActionResult Create()
{
if (Session["AdminName"] != null)
{
//ViewBag.Investors = SelectListItems;
List<FounderInvestmentViewModel> model = new List<FounderInvestmentViewModel>();
List<InstallmentDetailsViewModel> model2 = new List<InstallmentDetailsViewModel>();
return View(new PropertyViewModel());
}
else return Redirect("/Account/Login");
}
EDIT:-
Sorry this is what is throwing the exception -->> Collection.cshtml
PROCESS:- In the Main View, "Add Founder Investor Buttons" on click event adds the partial view _FounderInvestmentDetails.cshtml successfully.Now the "Add Installment Details" button is appended.Upon clicking this "Add Installment Details" button _InstallmentDetails.cshtml partial view should be appended,BUT this part is not working. When I click this button, I get the error "Object reference not set to an instance of an object" in the following code:-
#using HtmlHelpers.BeginCollectionItem
<ul>
#foreach (object item in Model)-->>ERROR CODE
{
<li>
#using (Html.BeginCollectionItem(Html.ViewData.TemplateInfo.HtmlFieldPrefix))
{
#Html.EditorFor(_ => item, null, "")
}
</li>
}
</ul>
The Paydates and Installments does not need to be <List> as it already is a PartialView and can be added multiple times.
public class InstallmentDetailsViewModel {
public int? Id { get; set; }
[Display(Name = "Pay Date")]
public List<DateTime> PayDates { get; set; }
[Required]
public List<double> InstallmentAmounts { get; set; }
}