How to get Model List in Controller - c#

I have this form in MVC Razor . The html is quite long so I am posting the area where I want to work
these are the checkboxes which are populated as service packages
The flow is the user will upload a photo and when proceeds to the next step it goes to a page where he will be selecting service for each photo if he has uploaded 3 photos the three photos will be having the same service
listing but different order IDS
I want is that when a user select services for a specific order means a specific order has multiple services . I want to map it so that Model List will be feteched in the Controller and I can easily insert in the database
this is the HTML:
#using (Html.BeginForm("PlaceOrder", "User", FormMethod.Post, new { id="ServiceForm",#class = "form-horizontal
white-clr", role = "form" }))
{
<!--If user has uploaded a single photo or multiple photo -->
<div class="window-for-choose-service">
#if (ViewBag.OrdersList != null)
{
int i= 1;
foreach (var d in ViewBag.OrdersList)
{
<div class="row">
<div class="col-sm-3 col-md-3 col-lg-3">
<img src="#d.ThumbnailPath" class="img-thumbnail img-responsive" width="250">
</div>
<div class="col-sm-9 col-md-9 col-lg-9">
<form class="white-clr" role="form">
<div class="form-group">
<label for="name">Description</label>
<textarea class="form-control" rows="4"></textarea>
</div>
</form>
</div>
<div class="col-sm-12 col-md-12 col-lg-12">
<div class="panel-group" id="accordion_#d.ID">
<div class="panel panel-primary">
#foreach (var Services in ViewBag.ServicePackages)
{
int cID = Services.ID + d.ID;
//int rndNumber = Convert.ToInt32(TimeSpan.FromSeconds(new Random().Next(0,
11221)).ToString("hmsf"));
if (Services.ServiceParentID == null)
{
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion_#d.ID"
href="#collapseOne_#cID">
#Services.ServiceName
</a>
</h4>
</div>
<div id="collapseOne_#cID" class="panel-collapse collapse in">
<div class="panel-body">
<div>
<div class="table-responsive">
#foreach (var child in Services.ft_service_packages1)
{
//string ness = "ServiceSelected[" + #d.ID + "]";
<div style="width:auto;min-width:250px;float:left; padding:4px; display:inline-block">
<div style="float:left;padding-right:5px;">
<label for="inlinecheckbox_#child.ID">
#Html.CheckBoxFor(m => m.ServiceSelect, new { id = "inlinecheckbox_" +
#child.ID, price_attr = "#child.ServicePrice"})
#Html.HiddenFor(m => m.UploadOrderID, new { Value = #d.ID })
</label>
</div>
<div style="padding-left:2px;">#child.ServiceName</div>
</div>
}
</div>
</div>
</div>
</div>
i++;
}
}
</div>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12"><p class="text-right font-blue"><b> Price $
0.0</b></p> </div>
</div>
}
}
The Html is genereting perfectly fine . But the thing is not getting anything in the controller regarding the model
Model is listed below
using System;
using System.Collections.Generic;
public partial class ft_order_itemized
{
public int ID { get; set; }
public int UploadOrderID { get; set; }
public int ServiceSelected { get; set; }
public decimal ServiceCharges { get; set; }
public System.DateTime ServiceSelectedDate { get; set; }
public Nullable<int> OrderID { get; set; }
public bool ServiceSelect { get; set; }
public virtual ft_orders ft_orders { get; set; }
public virtual ft_service_packages ft_service_packages { get; set; }
public virtual ft_uploads_orders ft_uploads_orders { get; set; }
}
My Controller :
[HttpPost]
public ActionResult PlaceOrder(ICollection<ft_order_itemized> Orders)
{
if (Orders.Count > 0)
{
}
// ICollection Allstrings = Orders["Service"].ToList();
return View();
}

Related

When i try to get data from data for edit page it's showing me error

When I try to get data from data for edit page it's showing me the following error:
So I am building a website where I want to implement a edit banner form when the User can Edit his banner data.
And here is where the problem I raise, when I run the code, it return always as null.
Here is my controller:
[HttpGet]
public ActionResult EditBanner(int id)
{
var abd = (from a in _db.Banner
where id == a.BannerId
select a).FirstOrDefault();
return View(abd);
}
[HttpPost]
public ActionResult UpdateBannerDatas(BannerViewModels bnrupdate)
{
var bnrdata = _db.Banner.Where(x => x.BannerId == bnrupdate.BannerId).FirstOrDefault();
if (bnrdata != null)
{
bnrdata.BannerTitle = bnrupdate.BannerTitle;
bnrdata.BannerUrl = bnrupdate.BannerUrl;
bnrdata.BannerIndex = bnrupdate.BannerIndex;
bnrdata.BannerDescription = bnrupdate.BannerDescription;
bnrdata.BannerIndex = bnrupdate.BannerIndex;
_db.SaveChanges();
}
return Redirect("BannerDetails");
}
Here is my viewmodel:
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SZGMC.Web.Models;
namespace SZGMC.Web.Areas.Admin.ViewModels
{
public class BannerViewModels
{
public int BannerId { get; set; }
public string BannerTitle { get; set; }
public string BannerDescription { get; set; }
public string BannerImg { get; set; }
public IFormFile BannerImg1 { get; set; }
public string BannerUrl { get; set; }
public string BannerIndex { get; set; }
public int? BMasterId { get; set; }
public byte? IsDeleted { get; set; }
public virtual BannerMaster BMaster { get; set; }
}
}
Here is my model:
using System;
using System.Collections.Generic;
// Code scaffolded by EF Core assumes nullable reference types (NRTs) are not used or disabled.
// If you have enabled NRTs for your project, then un-comment the following line:
// #nullable disable
namespace SZGMC.Web.Models
{
public partial class Banner
{
public int BannerId { get; set; }
public string BannerTitle { get; set; }
public string BannerDescription { get; set; }
public string BannerImg { get; set; }
public string BannerUrl { get; set; }
public string BannerIndex { get; set; }
public int? BMasterId { get; set; }
public byte? IsDeleted { get; set; }
public virtual BannerMaster BMaster { get; set; }
}
}
Here is my view:
<form asp-controller="Home" asp-action="UpdateBannerDatas" enctype="multipart/form-data" method="post">
<div id="main-content">
<div class="container-fluid">
<!-- Page header section -->
<div class="block-header">
<div class="row clearfix">
<div class="col-lg-6 col-md-5 col-sm-12">
<h1>Hi, Welcomeback!</h1>
<span>You can edit banner here</span>
</div>
<div class="col-xl-6 col-md-7 col-sm-12 text-md-right">
<div class="d-flex align-items-center justify-content-md-end mt-4 mt-md-0 flex-wrap vivify pullUp delay-550">
<div class="mb-3 mb-xl-0 ">
<a asp-action="BannerDetails" class="btn btn-dark">Banner List</a>
</div>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-12">
<div class="card">
<div class="body">
<div class="header">
<h2><strong>Enter Banner Details</strong></h2>
</div>
<br />
<input asp-for="BannerId" type="hidden" />
<div class="row">
<div class="col-12">
<div class="form-group c_form_group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"></span>
</div>
<input type="text" class="form-control" asp-for="BannerTitle" placeholder="Banner Title" aria-label="bannertitle" aria-describedby="basic-addon1">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group c_form_group">
<label>Banner Description</label>
<div class="input-group">
<textarea class="form-control" asp-for="BannerDescription" aria-label="Banner Description" rows="6"></textarea>
</div>
</div>
</div>
<div class="col-6">
<div class="drop-zone">
<span class="drop-zone__prompt">Drop file here or click to upload</span>
<input type="file" asp-for="BannerImg1" name="myFile" class="drop-zone__input" accept="image/*" data-allowed-file-extensions='["jpg", "png" , "jpeg"]' required>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group c_form_group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"></span>
</div>
<input type="text" class="form-control" asp-for="BannerIndex" placeholder="Banner Index" aria-label="bannerindex" aria-describedby="basic-addon1">
</div>
</div>
</div>
<div class="col-6">
<div class="form-group c_form_group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"></span>
</div>
</div>
</div>
</div>
</div>
<div class="mb-2" align="center">
<button type="submit" class="btn btn-success btn-round">Edit Banner</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
When i try To Edit the data in the browser it Throw exception, in database i have value but when i tried to fetch data its showing error.
thank you in advance to everybody for any help or advice.
According to the error message it is necessary to pass the BannerViewModels instance instead of the Banner entity:
public ActionResult EditBanner(int id)
{
var abd = _db.Banner.Where(a => a.BannerId == id)
.Select(b => new BannerViewModels()
{
BannerId = b.BannerId,
BannerTitle = b.BannerTitle,
BannerDescription = b.BannerDescription,
BannerImg = b.BannerImg,
BannerUrl = b.BannerUrl,
BannerIndex = b.BannerIndex,
BMasterId = b.BMasterId,
IsDeleted = b.IsDeleted
})
.FirstOrDefault();
return View(abd);
}
Passing an entity to the view as a data model is bad idea.
See the following post: Why it's not a good idea to pass entities as Models in MVC?

How To Get TreeView Model from view to controller on .net core 3.1 MVC

I have a .net core 3.1 MVC project where i am displaying a custom made treeview along with 2 textbox.
Here is the Model i used:
public class DeviceGroupAvailabilityModel
{
public string ChapterTitle { get; set; }
public string ChapterDetail { get; set; }
public List<TreeViewModel> TreeViewModels { get; set; }
}
And
public class TreeViewModel
{
public string ParentNode { get; set; }
public bool isChecked { get; set; }
public List<TreeViewModel> ChildNodes { get; set; }
}
Here is the function that i use to display the tree full on the cshtml file.
Here is part of the cshtml file:
here is my controller:
public async Task<IActionResult> Index()
{
List<TreeViewModel> TreeModel = BuildModels(await prtgClient.GetExtendedGroupsAsync(_pRTGApiClient),1);
DeviceGroupAvailabilityModel deviceGroupAvailabilityModel = new DeviceGroupAvailabilityModel
{
ChapterTitle = "Device And Group Availability",
ChapterDetail = "",
TreeViewModels = TreeModel
};
return View("Index",deviceGroupAvailabilityModel);
}
public IActionResult Cancel()
{
return RedirectToAction("Index","Home");
}
[HttpPost]
public async Task<IActionResult> Save([FromForm]DeviceGroupAvailabilityModel deviceGroupAvailabilityModel)
{
int reportID = await _dbConnection.GetReportId(deviceGroupAvailabilityModel.ChapterTitle);
deviceGroupAvailabilityModel.TreeViewModels.Select(async group => await AddGroupToReport(group.ParentNode, reportID));
return View("Index");
}
private async Task AddGroupToReport(string groupName,int reportID)
{
int groupId = await _dbConnection.GetGroupId(groupName);
await _dbConnection.AddGroupToReport(groupId, reportID);
}
private List<TreeViewModel>BuildModels(List<ExtendedGroup>extendedGroups,int rootID)
{
List<TreeViewModel> TreeModel = new List<TreeViewModel>();
extendedGroups.ForEach(group =>
{
if (group.parentId == rootID)
{
TreeModel.Add(new TreeViewModel
{
ParentNode = group.name,
ChildNodes = BuildModels(extendedGroups, group.objid)
});
}
});
return TreeModel;
}
Model Binding from controller to view works great but from view to controller in only get the Two textbox not the list of treeview model.
Is there a way to solve this?
kind regards,
Edit: Full CSHTML Code withoud Title:
#model DeviceGroupAvailabilityModel
#functions{
void DisplayTree(List<TreeViewModel>models)
{
<ul>
#foreach (TreeViewModel treeViewModel in models)
{
<li>
<input type="checkbox" id="#treeViewModel.ParentNode" name="#treeViewModel.ParentNode" checked="#treeViewModel.isChecked" />
#treeViewModel.ParentNode
#if (treeViewModel.ChildNodes.Count > 0)
{
DisplayTree(treeViewModel.ChildNodes);
}
</li>
}
</ul>
}
}
#using (Html.BeginForm("Save", "DeviceGroupAvailability",FormMethod.Post)) {
<div class="container">
<div class="row">
<div class="col-auto">
<div class="card shadow" style="border-left-color:#0087e9;border-left-width:medium">
<h6 class="card-header text-center bg-warning">SELECT GROUP TO REPORT</h6>
<div class="card-body">
<div class="tree well">
#{
DisplayTree(Model.TreeViewModels);
}
</div>
</div>
</div>
</div>
<div class="col">
<div class="row">
<div class="card shadow ml-3 mb-3" style="border-left-color:#0087e9;border-left-width:medium">
<h6 class="card-header text-center bg-warning">CHAPTER TITLE</h6>
<div class="card-body">
#Html.TextBoxFor(m=>m.ChapterTitle)
</div>
</div>
</div>
<div class="row">
<div class="card shadow ml-3 mb-3" style="border-left-color:#0087e9;border-left-width:medium">
<h6 class="card-header text-center bg-warning">CHAPTER Description</h6>
<div class="card-body">
#Html.TextBoxFor(m=>m.ChapterDetail)
</div>
</div>
</div>
<div class="row">
<input type="submit" class="btn ml-5 bg-primary text-white" value="Save" />
<button type="button" class="btn bg-primary ml-5 text-white" onclick="location.href='#Url.Action("Cancel", "DeviceGroupAvailability")'">Cancel</button>
</div>
</div>
</div>
</div>
}
#section Scripts{
<script type="text/javascript">
$(":checkbox").change(function () {
//begin Cheking all child elements
var ulsiblings = $(this).siblings("ul");
var lichilt = ulsiblings.find("li");
var checkchild = lichilt.find(":checkbox");
checkchild.prop("checked", this.checked);
//begin checking Parent element
//if child is checked
var checkLiParent = $(this).parent();
var checkliSiblings = checkLiParent.siblings("li");
var lisibCheck = checkliSiblings.find(":checkbox");
var isAllChecked;
lisibCheck.each(function () {
if (this.checked) {
isAllChecked = true;
}
else {
isAllChecked = false;
}
})
if (isAllChecked) {
var checkParent = checkLiParent.parent();
var parentSib = checkParent.siblings(":checkbox");
parentSib.prop("checked", this.checked);
}
})
</script>
}

Changing Drop down list ASP.NET CORE

I am using ASP.NET CORE with SQL server.
I have 2 tables: Review and WorkSchedule. The WorkSchedule table contains ManagerID and StaffID. The Review table contains ReviewerID and RevieweeID. The ManagerID,StaffID,ReviewerIDandRevieweeID are foreign keys to StaffID in the Staff table.
For example, if I create a new review in the CreateReview page, I will manually set the ReviewerID and RevieweeID. I want to make the WorkScheduleID dropdown to automatically change so that WorkScheduleID will appear where ManagerID = ReviewerID and StaffID = RevieweeID
Model:
namespace Starbucks.Models
{
public class ReviewModel
{
[Key]
[Display(Name = "Review ID")]
public Guid ReviewID { get; set; }
[Display(Name = "Reviewer")]
public Guid ReviewerID { get; set; }
[ForeignKey("ReviewerID")]
public StaffModel Staff { get; set; }
[Display(Name = "Reviewee")]
public Nullable<Guid> RevieweeID { get; set; }
[ForeignKey("RevieweeID")]
public StaffModel Staffs { get; set; }
[Display(Name = "WorkSchedule ID")]
public Nullable<Guid> WorkScheduleID { get; set; }
[ForeignKey("WorkScheduleID")]
public WorkScheduleModel WorkSchedules { get; set; }
}
public class WorkScheduleModel
{
[Key]
[Display(Name = "Work Schedule ID")]
public Guid WorkScheduleID { get; set; }
[Display(Name = "Staff ID")]
public Nullable<Guid> StaffID { get; set; }
[ForeignKey("StaffID")]
public StaffModel Staffs { get; set; }
[Display(Name = "Manager ID")]
public Guid ManagerID { get; set; }
[ForeignKey("ManagerID")]
public StaffModel Staff { get; set; }
}
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateReview([Bind("ReviewID,ReviewCategoryID,ReviewRating,ReviewComment,ReviewDateTime,ReviewerID,RevieweeID,WorkScheduleID")] ReviewModel reviewModel)
{
if (ModelState.IsValid)
{
reviewModel.ReviewID = Guid.NewGuid();
reviewModel.ReviewDateTime = DateTime.Now;
_context.Add(reviewModel);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(ProfilePage));
}
ViewData["RevieweeID"] = new SelectList(_context.Staff, "StaffID", "StaffName", reviewModel.RevieweeID);
ViewData["ReviewerID"] = new SelectList(_context.Staff, "StaffID", "StaffName", reviewModel.ReviewerID);
ViewData["WorkScheduleID"] = new SelectList(_context.WorkSchedule, "WorkScheduleID", "WorkScheduleID");
return View(reviewModel);
}
View Page:
<body>
<div class="row">
<div class="col-md-8">
<form asp-action="CreateReview">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="ReviewerID" class="control-label"></label>
<select asp-for="ReviewerID" class="form-control" asp-items="ViewBag.ReviewerID"></select>
</div>
<div class="form-group">
<label asp-for="RevieweeID" class="control-label"></label>
<select asp-for="RevieweeID" class="form-control" asp-items="ViewBag.RevieweeID"></select>
</div>
<div class="form-group">
<label asp-for="WorkScheduleID" class="control-label"></label>
<select asp-for="WorkScheduleID" class="form-control" asp-items="ViewBag.WorkScheduleID"></select>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<input type="submit" value="Save" class="btn btn-primary btn-block" />
</div>
</div>
</form>
</div>
</div>
</body>
You can create a method to filter the data, and use ajax to call it, then populate the select list with the returned data.
Controller:
public IActionResult Index()
{
ViewData["RevieweeID"] = new SelectList(_context.Staff, "StaffID", "StaffName");
ViewData["ReviewerID"] = new SelectList(_context.Staff, "StaffID", "StaffName");
ViewData["WorkScheduleID"] = new SelectList(_context.WorkSchedule, "WorkScheduleID", "WorkScheduleID");
return View();
}
[HttpGet]
public IActionResult FilterWorkScheduleID(Guid reviewerid, Guid revieweeid)
{
var WorkScheduleIDs = _context.WorkSchedule.Where(x => x.StaffID == revieweeid && x.ManagerID == reviewerid).ToList();
return Json(new { items = WorkScheduleIDs });
}
View:
#model ReviewModel
#{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<div class="row">
<div class="col-md-8">
<form asp-action="CreateReview">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="ReviewerID" class="control-label"></label>
<select asp-for="ReviewerID" class="form-control" asp-items="ViewBag.ReviewerID"></select>
</div>
<div class="form-group">
<label asp-for="RevieweeID" class="control-label"></label>
<select asp-for="RevieweeID" class="form-control" asp-items="ViewBag.RevieweeID"></select>
</div>
<div class="form-group">
<label asp-for="WorkScheduleID" class="control-label"></label>
<select asp-for="WorkScheduleID" class="form-control" asp-items="ViewBag.WorkScheduleID"></select>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<input type="submit" value="Save" class="btn btn-primary btn-block" />
</div>
</div>
</form>
</div>
</div>
#section scripts{
<script>
$("select").on("change", function () {
var reviewerID = $("#ReviewerID").find(":selected").val();
var revieweeID = $("#RevieweeID").find(":selected").val();
$.ajax({
type: 'get',
url: '/Staff/FilterWorkScheduleID',
data: {
reviewerid: reviewerID,
revieweeid:revieweeID
},
success: function (result) {
$("#WorkScheduleID").empty();
$.each(result.items, function (i, obj) {
var option = "<option value=" + obj.workScheduleID + ">" + obj.workScheduleID + "</option>";
$(option).appendTo("#WorkScheduleID");
})
}
})
})
</script>
}
Result:

I want to import my related product by them tags

Thats my HomeViewModel:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GymInternetShop.ViewModels.Home
{
public class HomeIndexViewModel
{
public IEnumerable<GymInternetShop.Models.DomainModels.Group> Groups { get; set; }
public IEnumerable<GymInternetShop.Models.DomainModels.Product> Products { get; set; }
public IEnumerable<GymInternetShop.Models.DomainModels.Product> Papoular { get; set; }
public IEnumerable<GymInternetShop.Models.DomainModels.Product> SameProduct { get; set; }
public IEnumerable<GymInternetShop.Models.DomainModels.Product> BestSellersProducts { get; set; }
}
}
i wanna use public IEnumerable<GymInternetShop.Models.DomainModels.Product> SameProduct { get; set; } in my HomeIndexViewModel to show Related post on my bottom View Page.
Thats My Controller:
public ActionResult ShowProducts(string productName , string tags)
{
ProductRepository blProduct = new ProductRepository();
var model = new GymInternetShop.ViewModels.Home.HomeIndexViewModel();
model.SameProduct = blProduct.Select().Where(p => p.Tags == tags);
List<Product> src = blProduct.Where(p => p.Url.Trim() == productName.Trim()).ToList();
if (src.Any())
{
return View(src);
}
else
{
return RedirectToAction("Index");
}
}
i created that controller for when i push on Details Product Button i Redirect To
My ShowProductView Model and i can See my Product details,
My problem is here:i want Create a Div in Bottom of My ShowProductView Model to showing Related Post, i want select my Related post with Them Tags in My Sql
and thats my ShowProduct View Model:
#model IEnumerable<GymInternetShop.Models.DomainModels.Product>
#{
ViewBag.Title = "ShowProducts";
}
<div class="container">
<h2 >Product Details</h2>
<div class="separator"></div>
</div>
//Note: Here i show My Details Product And Thats Work!
#foreach (var item in Model)
{
<div class="container" dir="rtl">
<div class="card">
<div class="container-fliud">
<div class="wrapper row">
<div class="preview col-md-6">
<div class="preview-pic tab-content">
<div class="tab-pane active" id="pic-1"><img src="/Files/UploadImages/#item.Image" /></div>
<div class="tab-pane" id="pic-2"><img src="/Files/UploadImages/#item.Image" /></div>
<div class="tab-pane" id="pic-3"><img src="/Files/UploadImages/#item.Image" /></div>
<div class="tab-pane" id="pic-4"><img src="/Files/UploadImages/#item.Image" /></div>
<div class="tab-pane" id="pic-5"><img src="/Files/UploadImages/#item.Image" /></div>
</div>
</div>
</div>
</div>
</div>
</div>
}
// note: I want to make a Foreach Here and Select my Related Post Where My post Tags looklike My Above product Tags

EditorForTemplate inside a DisplayForTemplate MVC Razor

I was trying to use Html Display For Template for looping through a Model data. Inside my Display template, I wanted to use an EditorFor template that would display a different set of data, In doing so, I was running into issues where my child model was empty. Upon playing around and getting guidance from David, I was able to make this to work. Below, please find my updated working solution.
UPDATE (Correct solution)
public class TargetingAreaViewModel
{
public int DealerId { get; set; }
public int OrderId { get; set; }
public List<TargetingAreaOrderItemViewModel> TargetingAreaOrderItems { get; set; }
public TargetingAreaViewModel()
{
this.TargetingAreaOrderItems = new List<TargetingAreaOrderItemViewModel>();
}
}
public class TargetingAreaOrderItemViewModel
{
public int OrderItemId { get; set; }
public int PackageMediaTypeId { get; set; }
public string PackageMediaTypeHeader { get; set; }
public string MediaTypeDesc { get; set; }
public string TargetingAdditonalInfo { get; set; }
public List<TargetingAreaItemViewModel> TargetingAreaItems { get; set; }
public TargetingAreaOrderItemViewModel()
{
this.TargetingAreaItems = new List<TargetingAreaItemViewModel>();
}
}
public class TargetingAreaItemViewModel
{
public int OrderItemId { get; set; }
public int PackageMediaTargetingFieldId { get; set; }
public string TargetingAreaFieldTitle { get; set; }
public string TargetingValue { get; set; }
public bool IsEnabled { get; set; }
public bool IsRequired { get; set; }
public string Comment { get; set; }
}
Parent View
#model Models.TargetingAreaViewModel
#{
ApplicationContext.Current.PageTitle = "Targeting Info";
Layout = "~/Views/Shared/MainLayout.cshtml";
}
#using (Html.BeginForm("OrderItemTargetingInfo", "Home", FormMethod.Post, new { #class = "form-horizontal" }))
{
#Html.DisplayFor(m => m.TargetingAreaOrderItems)
<div class="col-sm-12">
<div class="pull-right">
<input id="Submit" type="submit" value="Submit" class="btn btn-primary" />
</div>
</div>
}
DisplayFor Template View
#model Models.TargetingAreaOrderItemViewModel
<div class="row">
<div class="col-sm-12">
<div class="col-sm-12 btn-primary" style="margin-bottom: 10px; margin-top: 10px;">
#Html.Label(Model.MediaTypeDesc, new { #style = "font-weight: bold; padding-top: 10px; font-size: 18px;" })
#Html.HiddenFor(m => m.OrderItemId)
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
#Html.Raw(Model.PackageMediaTypeHeader)
</div>
</div>
<br />
<div class="row">
<div class="col-sm-12">
#Html.EditorFor(m => m.TargetingAreaItems)
</div>
</div>
<br />
<div class="row">
<div class="col-md-12">
<div class="form-group">
#Html.Label("Additional Info:", new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.TextAreaFor(m => m.TargetingAdditonalInfo, new { #class = "form-control" })
</div>
</div>
</div>
</div>
Now, I am able to display the data, get the data out of my model on Post. Works great!!
In your parent views you are only passing in the TargetingAreaOrderItems of the model but the child view is expecting a TargetingAreaViewModel. Instead you should pass in the entire model:
#Html.DisplayFor(m => m)

Categories

Resources