I should expect to see a drop down box with items from the staff remembers table but instead my view does not render. This there for makes the page appear broken I was wondering also is their a way to get the error that caused the page not to render correclty.
#model FuelActivityTrackerDal.ViewModels.ActivityEditViewModal
<div class="container py-5">
<div class="row">
<div class="col-md-10 mx-auto">
<form>
<div class="form-group row">
<div class="col-sm-6">
<label for="inputFirstname">Activty Name</label>
#Html.TextBoxFor(model => model.Name, new { #class = "whatever-class", #cols = 10, #rows = 25 })
</div>
<div class="col-sm-3">
<label for="inputLastname">Activity Start Date</label>
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
#Html.TextAreaFor(model => model.Description, new { #class = "whatever-class", #cols = 10, #rows = 25 })
</div>
<div class="col-sm-3">
<label for="inputAddressLine2">HoursLeftOnProject </label>
<input type="text" class="form-control" id="inputAddressLine2" placeholder="HoursLeftOnProject ">
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
<label for="inputCity">Status </label>
<input type="text" class="form-control" id="inputCity" placeholder="Status ">
</div>
<div class="col-sm-3">
<label for="inputState">ActivityType </label>
<input type="text" class="form-control" id="inputState" placeholder="ActivityType ">
</div>
<div class="col-sm-3">
<label for="inputPostalCode">SOP</label>
<div class="form-group">
#Html.LabelFor(x => Model.StaffID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-5">
<div class="form-group">
#Html.LabelFor(x => Model.StaffID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-5">
#Html.DropDownListFor(x => Model.StaffID, new SelectList(Model.StaffMemmbers, "Value", "Text"), htmlAttributes: new { #class = "form-control", #id = "Region" })
#Html.ValidationMessageFor(x => x.StaffID, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
</div>
<button type="button" class="btn btn-primary px-4 float-right">Save</button>
<button type="button" class="btn btn-primary px-4 float-right">Cancel</button>
</form>
</div>
</div>
</div>
However I am using the ActivityEditViewModal to populate my view.
public class ActivityEditViewModal
{
public int ActivityHeaderId { get; set; } //(int, null)
public DateTime? ActivityDate { get; set; } //(date, null)
public string Name { get; set; } //(nvarchar(350), null)
public DateTime? ActivityEndDate { get; set; } //(datetime, null)
public string Description { get; set; } //(nvarchar(max), null)
public int? ActivityLinesId { get; set; } //(int, null)
public int? HoursLeftOnProject { get; set; } //(time(7), null)
public int Status { get; set; } //(nchar(10), null)
public int ActivityType { get; set; } //(int, null)
public DateTime? CreatedDate { get; set; } //(date, null)
public string CreatedBy { get; set; } //(nvarchar(50), null)
public bool? isActive { get; set; } //(bit, null)
public bool? isDeleted { get; set; } //(bit, null)
public bool? isArchived { get; set; } //(bit, null)
public int? SOP { get; set; } //(nvarchar(50), null)
public int? DepartmentId { get; set; } //(int, null)
public string EmployeeName { get; set; } //(nvarchar(301), null)
public string StaffName { get; set; }
public int StaffID { get; set; }
public IEnumerable<SelectListItem> StaffMemmbers { get; set; }
}
In my Activity Repo I am populating the staff members are such which you can see from screen shot is working.
public List<ActivityEditViewModal> GetAllActivites()
{
var staffRepo = new StaffRepositry(_db);
List<ActivityHeader> activity = new List<ActivityHeader>();
activity = _db.ActivityHeader.AsNoTracking()
.Include(x => x.StaffMembers)
.ToList();
if (activity != null)
{
List<ActivityEditViewModal> activityDisplay = new List<ActivityEditViewModal>();
foreach (var x in activity)
{
var customerDisplay = new ActivityEditViewModal()
{
ActivityHeaderId = x.ActivityHeaderId,
ActivityDate =x.ActivityDate,
Name=x.Name,
ActivityEndDate = x.ActivityEndDate,
Description = x.Description,
StaffID =(int)x.StaffId
};
customerDisplay.StaffMemmbers = staffRepo.GetStaffs();
activityDisplay.Add(customerDisplay);
}
return activityDisplay;
}
return null;
}
public IEnumerable<SelectListItem> GetStaffs()
{
List<SelectListItem> staff = _db.Staff
.OrderBy(n => n.FirstName)
.Select(n =>
new SelectListItem
{
Value = n.StaffID.ToString(),
Text = n.FirstName + " " + n.LastName
}).ToList();
var staffip = new SelectListItem()
{
Value = null,
Text = "--- select staff ---"
};
staff.Insert(0, staffip);
return new SelectList(staff, "Value", "Text");
}
}
The result is a full broken page. When i take out the code for the dropdown it works fine.
Related
I have a class which has a collection of the activity lines of the heder which is a one to many linked by activitylines id.
public class ActivityHeader
{
public int ActivityHeaderId { get; set; } //(int, null)
public DateTime? ActivityDate { get; set; } //(date, null)
public string Name { get; set; } //(nvarchar(350), null)
public DateTime? ActivityEndDate { get; set; } //(datetime, null)
public string ProblemDescription { get; set; }
public string Description { get; set; } //(nvarchar(max), null)
public int? ActivityLinesId { get; set; } //(int, null)
public int? HoursLeftOnProject { get; set; } //(time(7), null)
public int? Status { get; set; } //(nchar(10), null)
public DateTime? CreatedDate { get; set; } //(date, null)
public string CreatedBy { get; set; } //(nvarchar(50), null)
public bool? isActive { get; set; } //(bit, null)
public bool? isDeleted { get; set; } //(bit, null)
public bool? isArchived { get; set; } //(bit, null)
public int? SOP { get; set; } //(nvarchar(50), null)
public int? OnSite { get; set; }
public int? Remote { get; set; }
public int? DepartmentId { get; set; } //(int, null)
public string EmployeeName { get; set; } //(nvarchar(301), null)
[ForeignKey("StaffId")]
public int? StaffId { get; set; }
public virtual StaffMembers StaffMembers { get; set; }
public ICollection<ActivityLines> ActivityLines { get; set; }
}
Activity Lines classs
public class ActivityLines
{
[Key]
public int ActivityLineId { get; set; } //(int, not null)
public int ActivitiyHeadId { get; set; } //(int, null)
public string Description { get; set; } //(nvarchar(max), null)
public string Notes { get; set; } //(nvarchar(max), null)
public DateTime StartTime { get; set; } //(time(7), null)
public DateTime EndTime { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; } //(time(7), null)
public int? StaffMemeber { get; set; } //(int, null)
public bool? isActive { get; set; } //(bit, null)
public bool? isDeleted { get; set; } //(bit, null)
public string CreatedBy { get; set; } //(nvarchar(50), null)
public DateTime? CreatedDate { get; set; } //(date, null)
public int? Status { get; set; } //(int, null)
}
However as you see it not allowing me to link without going to the first record using linq what is the best practise in being able to reference the lines correclty.
#model ActivityTrackerDal.ViewModels.ActivityEditViewModal
<div class="container py-5">
<div class="row">
<div class="col-md-10 mx-auto">
<form>
<div class="form-group row">
<div class="col-sm-9">
<label for="inputFirstname">Activty Name</label>
<input type="text" class="form-control" id="inputFirstname" placeholder="Activity name">
</div>
</div>
<div class="form-group row">
<div class="col-sm-3">
<label for="inputLastname" class="form-control">Activity Start Date</label>
#Html.Kendo().DateTimePickerFor(model => model.ActivityDate)
</div>
<div class="col-sm-3">
<label for="inputLastname" class="form-control">Activity End Date</label>
#Html.Kendo().DateTimePickerFor(model => model.ActivityEndDate)
</div>
</div>
<div class="form-group row">
<div class="col-sm-3">
<label for="inputLastname" class="form-control">Location</label>
#foreach (var item in (SelectList)ViewBag.Location)
{
#Html.RadioButtonFor(model => model.OnSite, item.Value, false)
<label class="control-label">#item.Text</label>
}
</div>
</div>
<div class="form-group row">
<div class="col-md-10">
<label for="inputLastname" class="form-control">Description</label>
#Html.TextAreaFor(model => model.Description, new { #class = "whatever-class", #cols = 115, #rows = 10 })
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
<label for="inputCity">Status </label>
<select asp-for="Status"
class="form-control"
asp-items="#(new SelectList(#ViewBag.ProjectStatusTypes,"LookupCode", "LookupDescription"))"></select>
</div>
<div class="col-sm-3">
<label for="inputState">ActivityType </label>
<select asp-for="ActivityType"
class="form-control"
asp-items="#(new SelectList(#ViewBag.ProjectTypes,"LookupCode", "LookupDescription"))"></select>
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
<label for="inputCity">Staff </label>
<select asp-for="StaffID"
class="form-control"
asp-items="#(new SelectList(#ViewBag.ListOfStaff,"StaffID", "FirstName"))"></select>
</div>
<div class="col-sm-3">
<label for="inputState">Hours Left On Project </label>
<label for="inputState"><div class="badge" style="font-size:18px;">26</div> </label>
<label for="projecthours">If Porject hours fall below ten Contact Charlie.</label>
</div>
</div>
<div class="form-group row">
<div class="col-sm-12">
#(Html.Kendo().Grid<FuelActivityTrackerDal.Models.ActivityLines>().Name("activityLines")
.Columns(columns =>
{
columns.Bound(p => p.Description).Filterable(false);
columns.Bound(p => p.StartTime).Filterable(false);
columns.Bound(p => p.EndTime).Filterable(false);
columns.Bound(p => p.Status);
columns.Command(command => command.Custom("ViewDetails").Click("showDetails"));
})
.DataSource(dataSource => dataSource
.Ajax()
.Events(events => events.Error("error_handler"))
.Model(model => model.Id(p => p.ActivityLineId))
.Read(read => read.Action("ActivityLines_Read", "Activity"))))
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
</div>
</div>
<button type="button" class="btn btn-primary px-4 float-right">Add Work Item</button>
<button type="button" class="btn btn-primary px-4 float-right">Put Case & Client On Hold</button>
<button type="button" class="btn btn-primary px-4">Cancel</button>
</form>
</div>
</div>
#(Html.Kendo().Window().Name("Details")
.Title("Activity Details")
.Visible(false)
.Modal(true)
.Draggable(true)
.Width(400)
)
<script type="text/x-kendo-template" id="template">
<form method="post" action="#Url.Action("SaveWorkItem", "Activity")">
<div id="details-container">
ActivitiyHeadId
<div class="form-group row">
<div class="col-sm-9">
<label for="inputFirstname">Activty Name</label>
<input type="text" class="form-control" id="inputFirstname" placeholder="Activity name">
</div>
</div>
<div class="form-group row">
<div class="col-md-10">
<label for="inputLastname" class="form-control">Description</label>
#Html.Kendo().TimePickerFor(model => model.ActivityLines.First(), new { #class = "whatever-class", #cols = 115, #rows = 10 })
</div>
</div>
<div class="form-group row">
<div class="col-md-6">
<label for="inputLastname" class="form-control">Start Time</label>
</div>
<div class="col-md-6">
<label for="inputLastname" class="form-control">End Time </label>
</div>
</div>
</div>
<input type="submit" class="btn btn-file px-4" value="Save Work Item" />
<button type="button" class="btn btn-primary px-4">Cancel</button>
</form>
</script>
<script type="text/javascript">
var detailsTemplate = kendo.template($("#template").html());
function showDetails(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var wnd = $("#Details").data("kendoWindow");
wnd.content(detailsTemplate(dataItem));
wnd.center().open();
}
</script>
</div>
Its this popup within I am having the issue with being able to reference the the activity lines
<script type="text/x-kendo-template" id="template">
<form method="post" action="#Url.Action("SaveWorkItem", "Activity")">
<div id="details-container">
ActivitiyHeadId
<div class="form-group row">
<div class="col-sm-9">
<label for="inputFirstname">Activty Name</label>
<input type="text" class="form-control" id="inputFirstname" placeholder="Activity name">
</div>
</div>
<div class="form-group row">
<div class="col-md-10">
<label for="inputLastname" class="form-control">Description</label>
#Html.Kendo().TimePickerFor(model => model.ActivityLines.First(), new { #class = "whatever-class", #cols = 115, #rows = 10 })
</div>
</div>
<div class="form-group row">
<div class="col-md-6">
<label for="inputLastname" class="form-control">Start Time</label>
</div>
<div class="col-md-6">
<label for="inputLastname" class="form-control">End Time </label>
</div>
</div>
</div>
<input type="submit" class="btn btn-file px-4" value="Save Work Item" />
<button type="button" class="btn btn-primary px-4">Cancel</button>
</form>
</script>
This is the main block from above I am having the issue with.
<div class="form-group row">
<div class="col-md-10">
<label for="inputLastname" class="form-control">Description</label>
#Html.Kendo().TimePickerFor(model => model.ActivityLines.First(), new { #class = "whatever-class", #cols = 115, #rows = 10 })
</div>
</div>
Do I need to use include here on the ActivityHeader get statement like I have done for the staff?.
public List<ActivityEditViewModal> GetAllActivites()
{
var staffRepo = new StaffRepositry(_db);
List<ActivityHeader> activity = new List<ActivityHeader>();
activity = _db.ActivityHeader.AsNoTracking()
.Include(x => x.StaffMembers)
.ToList();
if (activity != null)
{
List<ActivityEditViewModal> activityDisplay = new List<ActivityEditViewModal>();
foreach (var x in activity)
{
var customerDisplay = new ActivityEditViewModal()
{
ActivityHeaderId = x.ActivityHeaderId,
ActivityDate = x.ActivityDate,
Name = x.Name,
ActivityEndDate = x.ActivityEndDate,
Description = x.Description
};
activityDisplay.Add(customerDisplay);
}
return activityDisplay;
}
return null;
}
Ok So this is what I had to do I had to use the function called include which is explained in this article on Microsoft web site. Its called defered loading and by the reason of this is EF6 used to take forever to load one to many relationships actually a problem i had with an old app as EF6 uses lazy loading which always loaded all one to many relationships now you can load them when you require them.
https://learn.microsoft.com/en-us/ef/core/querying/related-data
public List<ActivityEditViewModal> GetAllActivites()
{
var staffRepo = new StaffRepositry(_db);
List<ActivityHeader> activity = new List<ActivityHeader>();
activity = _db.ActivityHeader.AsNoTracking()
.Include(x => x.StaffMembers)
.Include(x=>x.ActivityLines)
.ToList();
if (activity != null)
{
List<ActivityEditViewModal> activityDisplay = new
List<ActivityEditViewModal>();
foreach (var x in activity)
{
var customerDisplay = new ActivityEditViewModal()
{
ActivityHeaderId = x.ActivityHeaderId,
ActivityDate = x.ActivityDate,
Name = x.Name,
ActivityEndDate = x.ActivityEndDate,
Description = x.Description,
ActivityLines = x.ActivityLines
};
activityDisplay.Add(customerDisplay);
}
return activityDisplay;
}
I have a list inside ViewModel but when I make the Post to the Controller it's not binding it and shows an error on Parameter: null, Value: Null.
If you could help me out on this.
ViewModel:
public class OperaRateImportRuleViewModel
{
public SelectList ResortsSelectList { get; set; }
[Required]
[DisplayName("Resorts")]
public List<string> ListResort { get; set; }
public List<Rules> ExtraRuleList { get; set; }
public OperaRateImportRuleViewModel()
{
ExtraRuleList = new List<Rules>();
ListResort = new List<string>();
}
}
Controller:
public ActionResult EditRules(string id)
{
OperaRateImportRuleViewModel model = new OperaRateImportRuleViewModel();
var getRulesForResort = service.GetAllOperaRateRules().Where(x => x.ResortCode == id).ToList();
foreach (var item in getRulesForResort)
{
var ruleModel = new Rules()
{
Id = item.Id,
IsReferenceRule = item.IsReferenceRule,
PercentVariation = item.PercentVariation == null ? 0 : Decimal.Round(item.PercentVariation.Value, 2),
RateCode = item.RateCode,
ResortCode = item.ResortCode,
RoomType = item.RoomType,
SingleRoomDifference = item.SingleRoomDifference == null ? 0 : Decimal.Round(item.SingleRoomDifference.Value, 2),
SupplementValue = item.SupplementValue == null ? 0 : Decimal.Round(item.SupplementValue.Value, 2)
};
model.ExtraRuleList.Add(ruleModel);
}
return View(model);
}
[HttpPost]
public ActionResult EditRules(OperaRateImportRuleViewModel model)
{
foreach (var item in model.ExtraRuleList)
{
var rule = service.GetAllOperaRateRules().Where(x => x.Id == item.Id).FirstOrDefault();
rule.RateCode = item.RateCode;
rule.ResortCode = item.ResortCode;
rule.RoomType = item.RoomType;
rule.PercentVariation = item.PercentVariation;
rule.SupplementValue = item.SupplementValue;
rule.SingleRoomDifference = item.SingleRoomDifference;
rule.IsReferenceRule = item.IsReferenceRule;
service.Edit(rule);
}
return RedirectToAction("ManageRules");
}
And finally my View:
for (int i = 0; i < Model.ExtraRuleList.Count; i++)
{
#Html.HiddenFor(x => Model.ExtraRuleList[i].Id)
<div class="row">
<div class="col-md-2">
<div class="form-group">
#Html.TextBoxFor(x => x.ExtraRuleList[i].ResortCode, new { #class = "form-control" })
</div>
</div>
<div class="col-md-2">
<div class="form-group">
#Html.TextBoxFor(x => x.ExtraRuleList[i].ResortCode, new { #class = "form-control" })
</div>
</div>
<div class="col-md-2">
<div class="form-group">
#Html.TextBoxFor(x => x.ExtraRuleList[i].RoomType, new { #class = "form-control" })
</div>
</div>
<div class="col-md-1">
<div class="form-group">
#Html.TextBoxFor(x => x.ExtraRuleList[i].PercentVariation, new { #class = "form-control textBoxSize" })
</div>
</div>
<div class="col-md-1">
<div class="form-group">
#Html.TextBoxFor(x => x.ExtraRuleList[i].SupplementValue, new { #class = "form-control textBoxSize" })
</div>
</div>
<div class="col-md-1">
<div class="form-group">
#Html.TextBoxFor(x => x.ExtraRuleList[i].SingleRoomDifference, new { #class = "form-control textBoxSize" })
</div>
</div>
<div class="col-md-1">
<div class="form-group">
#Html.LabelFor(m => m.ExtraRuleList[i].IsReferenceRule, new { #class = "checkbox-label" })
#Html.CheckBoxFor(x => x.ExtraRuleList[i].IsReferenceRule)
</div>
</div>
<div class="col-xs-2">
<div class="form-group">
<span id="deleteSeason" title="Delete" onclick="$(this).closest('.row').remove().trigger(review());" class="glyphicon glyphicon-remove text-danger row-action"></span><span> </span>
</div>
</div>
</div>
}
<input type="submit" value="Edit" class="btn btn-primary" />
Back
Error:
Error when Binding
Much appreciated!
Thanks :)
EDIT
ViewModel Rules:
public class Rules
{
public int Id { get; set; }
[DisplayName("Rate Code")]
public string RateCode { get; set; }
[DisplayName("Resort Code")]
public string ResortCode { get; set; }
[DisplayName("Room Type")]
public string RoomType { get; set; }
[DisplayName("Percent Variation")]
public decimal? PercentVariation { get; set; }
[DisplayName("Supplement Value")]
public decimal? SupplementValue { get; set; }
[DisplayName("Single Room Difference")]
public decimal? SingleRoomDifference { get; set; }
[DisplayName("")]
public bool IsReferenceRule { get; set; }
public string HotelString { get; set; }
}
Your error is thrown because your IsReferenceRule property is decorated with [DisplayName("")]. You need to either delete it, or give it a value, for example
[DisplayName("Is Reference Rule ")]
public bool IsReferenceRule { get; set; }
but in any case, you should be using the DisplayAttribute, not the DisplayNameAttribute
[Display(Name = "Is Reference Rule ")]
Specifically, the error occurs when the public override IEnumerable<ModelValidationResult> Validate(object container) method of DataAnnotationsModelValidator is called. The offending line in the source code is context.DisplayName = Metadata.GetDisplayName(); which returns null because of the missing value in the attribute.
I'm using MVC 4. I make it in partial view because in one form I want to insert a lot of data to other database in one time. But when I insert the data, it successfully inserts but the data that I take from textbox is always empty, only data that has been initialized can be inserted. It can be inserted successfully but the data is always empty.
Model
namespace admission.Models
{
public class AlamatRumahModel
{
public int id_alamat_rumah { get; set; }
public string alamat_lengkap { get; set; }
public string provinsi { get; set; }
public string kota { get; set; }
public string kode_pos { get; set; }
public string telepon_rumah { get; set; }
public string hp { get; set; }
public string fax { get; set; }
public string email { get; set; }
public DateTime created { get; set; }
public string createdBy { get; set; }
public DateTime modified { get; set; }
public string modifiedBy { get; set; }
}
}
Controller
[HttpPost]
public ActionResult IRumah(AlamatRumahModel model)
{
Tbl_Alamat_Rumah rumah = new Tbl_Alamat_Rumah();
model = new AlamatRumahModel();
using (pmbEntities db = new pmbEntities())
{
int LastRumah = db.Tbl_Alamat_Rumah.Max(r => r.id_alamat_rumah);
rumah.id_alamat_rumah = LastRumah+ 1;
rumah.alamat_lengkap = model.alamat_lengkap;
rumah.provinsi= Request["propinsiR"];
rumah.kota = Request["kotaR"];
rumah.kode_pos = model.kode_pos;
rumah.telepon_rumah = model.telepon_rumah;
rumah.hp = model.hp;
rumah.fax = model.fax;
rumah.email = model.email;
rumah.created = DateTime.Now;
rumah.modified = DateTime.Now;
rumah.createdBy = "";
rumah.modifiedBy = "";
db.Tbl_Alamat_Rumah.Add(rumah);
db.SaveChanges();
return View();
}
}
[HttpPost]
public ActionResult InsertDataDiri(DataDiriModel model, AlamatRumahModel rumah, AlamatSuratModel surat, CpModel cp)
{
IDataDiri(model);
IRumah(rumah);
ISurat(surat);
IcP(cp);
return RedirectToAction("InsertRiwayatPendidikan", "User");
}
View
#model admission.Models.AlamatRumahModel
#using (Html.BeginForm("IRumah", "User", FormMethod.Post))
{
<fieldset>
<div class="col-xs-12">
<div class="col-md-12">
<br><br>
<legend>
<h3><span>Alamat Rumah<i class="arrow-down"></i></span></h3>
</legend>
<br>
<!-- Text input-->
<div class="content">
<div class="form-group">
<label class="col-md-4 control-label">Alamat Lengkap</label>
<div class="col-md-5">
#Html.TextAreaFor(model => model.alamat_lengkap, new { #class = "form-control input-md", #autocomplete = "off"})
</div>
</div>
<br>
<br>
<br />
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="stack_id">Propinsi</label>
<div class="col-md-5">
#(Html.Kendo().DropDownList()
.Name("propinsiR")
.OptionLabel("Please select Branch ...")
.HtmlAttributes(new { style = "width:100%" })
.DataTextField("Text")
.DataValueField("Value")
.Filter("contains").DataSource(source => { source.Read(read => read.Action("GetProvinsiByJSON", "Lokasi")); })
)
</div>
</div>
<br>
<br>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="stack_id">Kota</label>
<div class="col-md-5">
#(Html.Kendo().DropDownList()
.Name("kotaR")
.OptionLabel("Please select Branch ...")
.HtmlAttributes(new { style = "width:100%" })
.DataTextField("Text")
.DataValueField("Value")
.Filter("contains").DataSource(source => { source.Read(read => read.Action("GetKotaByJSON", "Lokasi")); })
)
</div>
</div>
<br>
<br>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="cmpny">Kode Pos</label>
<div class="col-md-5">
#Html.TextBoxFor(model => model.kode_pos, "", new { #class = "form-control input-md", #autocomplete = "off" })
</div>
</div>
<br>
<br>
This is what I get in my db:
I just noticed in your controller that you are instantiating the model again.
[HttpPost]
public ActionResult IRumah(AlamatRumahModel model)
{
Tbl_Alamat_Rumah rumah = new Tbl_Alamat_Rumah();
model = new AlamatRumahModel(); //Remove this line of code
using (pmbEntities db = new pmbEntities())
{
...
That's why you lost the values of your model. Remove that line of code, and it should work fine.
I have following get method to add a form data and edit form data
Also have table call AB_Product_vs_Field in that table I have following columns
Product_ID
Field_ID
Field_Value_EN
Field_Value_AR
once I pass Product_ID and Field_ID page number it can find if there any record exist in AB_Product_vs_Field
if it has a specific record I can load relevant values
else it doesn't have a record I can load insert as a new record
[HttpGet]
public ActionResult Add_Field_Values(int? page, string Product_ID,string FieldID)
{
var pager = new PaginationModel.Pager(dummyItems.Count(), page);
ViewBag.Product_ID = Product_ID;
ViewBag.FieldID = FieldID;
//check specific row exist or not in AB_Product_vs_Field table
if ((db.AB_Product_vs_Field.Any(u => u.Product_ID == Product_ID)) & (db.AB_Product_vs_Field.Any(u => u.Field_ID == FieldID)))
{
//edit a product field values
var product_values = new ProductEdit
{
ListProductFields = db.AB_Product_vs_Field.Where((p => p.Field_ID == FieldID)).Where(p => p.Product_ID == Product_ID).ToList(),
ListProductLables = db.AB_ProductTypeCategoryField.Where(p => p.ProductFieldID == FieldID).ToList(),
Pager = pager,
};
return View("~/Views/Home/Edit_Field_Values.cshtml", product_values);
}
else
{
//add new product field values
var model = new AddNewProduct
{
ListProductFields_Add = db.AB_ProductTypeCategoryField.OrderBy(i => i.ProductFieldID).Skip((pager.CurrentPage - 1) * pager.PageSize).Take(pager.PageSize).ToList(),
Pager = pager
};
return View(model);
}
}
theses are the the models that relate to above controller
AddNewProduct model class
public class AddNewProduct
{
public string Product_ID { get; set; } }
public string Field_ID { get; set; }
public string ProductFieldNameEn { get; set; }
public string ProductFieldNameAr { get; set; }
public IList<AB_ProductTypeCategoryField> ListProductFields { get; set; }
public IEnumerable<string> Items { get; set; }
public PaginationModel.Pager Pager { get; set; }
public int PageSize { get; set; }
public int PageCount { get; set; }
public int CurrentPageIndex { get; set; }
}
this is ProductEdit model class
public class ProductEdit
{
public string Product_ID { get; set; }
public string Field_ID { get; set; }
public string ProductFieldNameEn { get; set; }
public string ProductFieldNameAr { get; set; }
public IList<AB_Product_vs_Field> ListProductFields { get; set; }
public IList<AB_ProductTypeCategoryField> ListProductLables { get; set; }
public IEnumerable<string> Items { get; set; }
public PaginationModel.Pager Pager { get; set; }
public int PageSize { get; set; }
public int PageCount { get; set; }
public int CurrentPageIndex { get; set; }
}
this is the view of Add New Product
#model project_name.Models.AddNewProduct
<h4>Add New Product</h4>
#using (Html.BeginForm("Add_Field_Values", "Home", new { Product_ID = ViewBag.Product_ID }, FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div style="visibility:hidden"> #ViewBag.Product_ID </div>
<div style="visibility:hidden"> #ViewBag.FieldID </div>
#for (int i = 0; i < Model.ListProductFields.Count; i++)
{
<div class="form-group">
#Html.LabelFor(x => x.ListProductFields[i].ProductFieldNameEn, Model.ListProductFields[i].ProductFieldNameEn, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.HiddenFor(m => m.ListProductFields[i].ProductFieldID
#Html.TextAreaFor(m => m.ListProductFields[i].Field_Value_EN, new { #class = "form-control summernote", #row = 5 })
</div>
</div>
<div class="form-group">
#Html.LabelFor(x => x.ListProductFields[i].ProductFieldNameAr, Model.ListProductFields[i].ProductFieldNameAr, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.HiddenFor(m => m.ListProductFields[i].ProductFieldID)
#Html.TextAreaFor(m => m.ListProductFields[i].Field_Value_AR, new { #class = "form-control summernote", #row = 5 })
</div>
</div>
<!-- pagination section -->
<div class="form-group">
<div class="col-md-10">
<!-- pager -->
#if (Model.Pager.EndPage > 1)
{
<ul class="pagination">
#if (Model.Pager.CurrentPage > 1)
{
<li>
First
</li>
<li>
Previous
</li>
}
#for (var page = Model.Pager.StartPage; page <= Model.Pager.EndPage; page++)
{
<li class="#(page == Model.Pager.CurrentPage ? "active" : "")">
#page
</li>
}
#if (Model.Pager.CurrentPage < Model.Pager.TotalPages)
{
<li>
Next
</li>
<li>
Last
</li>
}
</ul>
}
</div>
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save Details" class="btn btn-success" />
</div>
</div>
}
</div> }
#section scripts{}
this is Edit view of product field values
#model project_name.Models.ProductEdit
<h4>Add New Product</h4>
#using (Html.BeginForm("Add_Field_Values", "Home", new { Product_ID = ViewBag.Product_ID }, FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div style="visibility:hidden"> #ViewBag.Product_ID </div>
<div style="visibility:hidden"> #ViewBag.FieldID </div>
<div class="form-group">
#Html.LabelFor(x => x.ListProductLables[0].ProductFieldNameEn, Model.ListProductLables[0].ProductFieldNameEn, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.HiddenFor(m => m.ListProductFields[0].Field_ID)
#if (Model.ListProductFields[0].Field_ID == "F000014" | Model.ListProductFields[0].Field_ID == "F000015")
#Html.TextAreaFor(m => m.ListProductFields[0].Field_Value_EN, new { #class = "form-control summernote", #row = 5 })
</div>
</div>
<div class="form-group">
#Html.LabelFor(x => x.ListProductLables[0].ProductFieldNameAr, Model.ListProductLables[0].ProductFieldNameAr, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.HiddenFor(m => m.ListProductFields[0].Field_ID)
#Html.TextAreaFor(m => m.ListProductFields[0].Field_Value_AR, new { #class = "form-control summernote", #row = 5 })
</div>
</div>
<!-- pagination section -->
<div class="form-group">
<div class="col-md-10">
<!-- pager -->
#if (Model.Pager.EndPage > 1)
{
<ul class="pagination">
#if (Model.Pager.CurrentPage > 1)
{
<li>
First
</li>
<li>
Previous
</li>
}
#for (var page = Model.Pager.StartPage; page <= Model.Pager.EndPage; page++)
{
<li class="#(page == Model.Pager.CurrentPage ? "active" : "")">
#page
</li>
}
#if (Model.Pager.CurrentPage < Model.Pager.TotalPages)
{
<li>
Next
</li>
<li>
Last
</li>
}
</ul>
}
</div>
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save Details" class="btn btn-success" />
</div>
</div>
</div>
}
#section scripts{}
This add view supposed to add record one by one upto 15 record per one product , those values are save to AB_Product_vs_Field for first record its working. but once I click next or number 2 I'm getting following error
Index was out of range. Must be non-negative and less than the size of
the collection. Parameter name: index
error occur in this line
#Html.HiddenFor(m => m.ListProductFields[0].Field_ID)
in Add_Field_Values page
I have ViewModel which contains some proprty of class. Code below.
public class ViewModel
{
public Doctor VmDoctor { get; set; }
public Patient VmPatient { get; set; }
public List<Visit> VmVisit { get; set; }
public List<Hours> hours { get; set; }
public List<Hours> hours2 { get; set; }
public Schedule schedule { get; set; }
public bool BlockBtn { get; set; }
public Test test { get; set; }
}
In this case important property is Patient VmPatient. This is a model which has been generated by Database Model First. He has validation.Code below.
public partial class Patient
{
public Patient()
{
this.Visits = new HashSet<Visit>();
}
public int PatientID { get; set; }
[Required(ErrorMessage = "Podaj imię.")]
public string name { get; set; }
[Required(ErrorMessage = "Podaj nazwisko.")]
public string surname { get; set; }
[Required(ErrorMessage = "Podaj pesel.")]
[RegularExpression(#"^\(?([0-9]{11})$", ErrorMessage = "Nieprawidłowy numer pesel.")]
public string pesel { get; set; }
[Required(ErrorMessage = "Podaj miasto.")]
public string city { get; set; }
[Required(ErrorMessage = "Podaj kod pocztowy.")]
public string zipCode { get; set; }
[Required(ErrorMessage = "Podaj e-mail.")]
[EmailAddress(ErrorMessage = "Nieprawidłowy adres e-mail")]
public string email { get; set; }
[Required(ErrorMessage = "Podaj telefon komórkowy.")]
[RegularExpression(#"^\(?([0-9]{9})$", ErrorMessage = "Nieprawidłowy numer telefonu.")]
public string phone { get; set; }
public virtual ICollection<Visit> Visits { get; set; }
}
and i have Main Index where return my ViewModel because, display two Models in the same View. Code below
public ActionResult Index(int id)
{
ViewModel _viewModle = new ViewModel();
schedule = new Schedule();
if(Request.HttpMethod == "Post")
{
return View(_viewModle);
}
else
{
idDr = id;
_viewModle.schedule = schedule;
_viewModle.BlockBtn = _repository.BlockBtn(schedule);
_viewModle.VmDoctor = db.Doctors.Find(idDr);
_viewModle.hours = _repository.GetHours();
foreach (var item in _viewModle.hours)
{
_viewModle.hours2 = _repository.GetButtonsActiv(item.hourBtn, item.count, idDr, schedule);
}
}
if (_viewModle == null)
{
return HttpNotFound();
}
return View(_viewModle);
}
inside View Index i display my objects and rendered partial _FormPatient.Code below.
#model Dentist.Models.ViewModel
<div class="container-select-doctor">
<div class="row">
<div class="text-left">
<div class="row">
<div class="content">
<div class="profileImage">
<div class="imageContener"><img style="margin:1px;" src="#Url.Content("~/Images/" + System.IO.Path.GetFileName(#Model.VmDoctor.image))" /></div>
</div>
<div class="profileInfo">
<div class="profileInfoName">#Model.VmDoctor.name #Model.VmDoctor.surname</div>
<div class="profileInfoSpeciality">#Model.VmDoctor.specialty</div>
</div>
</div>
</div>
</div>
#ViewBag.firstDay<br />
#ViewBag.lastDay<br />
<div class="text-middle">
<div class="content">
<div id="partialZone">
#Html.Partial("_TableSchedule")
</div>
</div>
</div>
<div class="text-right">
<div class="content">
#Html.Partial("_FormPatient")
</div>
</div>
</div>
</div>
and last step is form which has been rendered inside Main Index by #Html.partial.code below
#model Dentist.Models.ViewModel
#using (Html.BeginForm("Create","Patient"))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<font color="red">#ViewBag.Pesel</font>
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(model => model.VmPatient.email, htmlAttributes: new { #class = "control-label col-md-2" }, labelText: "E-mail:")
<div class="col-md-10">
#Html.TextBoxFor(model => model.VmPatient.email, new { htmlAttributes = new { #class = "form-control" } })
#*<input class="form-control" id="email" name="email" type="text" value="">*#
#Html.ValidationMessageFor(model => model.VmPatient.email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.VmPatient.phone, htmlAttributes: new { #class = "control-label col-md-2" }, labelText: "Telefon kom.:")
<div class="col-md-10">
#Html.TextBoxFor(model => model.VmPatient.phone, new { maxlength = 9 })
#*<input class="form-control" maxlength="9" id="phone" name="phone" type="text" value="" />*#
#Html.ValidationMessageFor(model => model.VmPatient.phone, "", new { #class = "text-danger" })
</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>
}
Please pay attention that this form redirect to another Controller where data will be validate and save to database. Method where data from FORM will be validate and save. code below
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Patient pat)
{
ViewModel vm = new ViewModel();
DentistEntities db = new DentistEntities();
if (ModelState.IsValid)
{
db.Patients.Add(pat);
db.SaveChanges();
}
return RedirectToAction("Index", "Visit", new { id = VisitController.idDr });
}
Conclusion How can i get validation for this form! I have observed that,every time modelstate.isvalid return false.. I dont have any ideas so I would like to ask you for help.
Best regards.
I would suggest that you do this:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Patient pat)
{
ViewModel vm = new ViewModel();
DentistEntities db = new DentistEntities();
if (ModelState.IsValid)
{
db.Patients.Add(pat);
db.SaveChanges();
}
vm.VmPatient = pat;
return View(vm);
}
Render the view again, but this time the validation error messages should appear on the page (via the ValidationMessageFor() calls in the view). That, at least you can see why the validation has failed.
Alternatively, you could interrogate the modelstate e.g.
foreach (ModelState modelState in ViewData.ModelState.Values) {
foreach (ModelError error in modelState.Errors) {
string error = error.ErrorMessage;
}
}