I'm only starting my adventure with programming, and currently im working on a e-commerce type of aplication in mvc. Recently i tried to make it possible to apply more then one photo and since then i have problems with controller that after clicking on the card was redirecting user to the product page. After click the error appears "System.InvalidOperationException: 'Nullable object must have a value.'" and it points to the values that have "null" value in database, but are not required and before it worked well, also it started showing a page with information that controller could not be found.
Below im showing my code. Thank you everyone in advance.
View
#model roomie.Models.Adviewmodel
#Styles.Render("~/Content/view_ad.css")
#Styles.Render("~/Content/layout.css")
<meta name="viewport" content="width=device-width" />
<title>ViewAd</title>
<div class="add-container">
<div class="add">
<div class="add_title">
<div> <p2> #Model.pro_name </p2> </div>
<div> <p3> AD-ID: #Model.pro_id </p3> </div>
</div>
<div class="pro_image_container">
<div class="pro_image">
#foreach (var image in Model.pro_img_path)
{
<img src="#Url.Content(image)" alt="Image" />
}
</div>
</div>
<div class="add_description">
<p4> Opis: </p4>
<p> #Model.pro_description</p>
</div>
<div class="add_details">
<table class="add_basic_info">
<tr> <td style="font-weight: bold;"> Cena: </td> <td> #Model.pro_price </td> </tr>
<tr> <td style="font-weight: bold;"> Kategoria: </td> <td> #Model.pro_type </td> </tr>
<tr> <td style="font-weight: bold;"> Adres: </td> <td> #Model.nazwa_miasta, #Model.pro_address_street #Model.pro_address_building_num, Piętro: #Model.pro_address_floor </td></tr>
<tr> <td style="font-weight: bold;"> Kontakt: </td> <td> #Model.user_contact </td> </tr>
</table>
<div> <p4> Co w mieszkaniu: </p4></div>
<div class="bool_info">
<div class="icon">
#if (#Model.pro_TV == true)
{
<img src="~/Content/img_icons/tv.png" />
}
</div>
<div class="icon">
#if (#Model.pro_ac == true)
{
<img src="~/Content/img_icons/ac.png" />
}
</div>
<div class="icon">
#if (#Model.pro_elevator == true)
{
<img src="~/Content/img_icons/elevator.png" />
}
</div>
<div class="icon">
#if (#Model.pro_handicapped == true)
{
<img src="~/Content/img_icons/hcp.png" />
}
</div>
<div class="icon">
#if (#Model.pro_internet == true)
{
<img src="~/Content/img_icons/internet.png" />
}
</div>
<div class="icon">
#if (#Model.pro_parking == true)
{
<img src="~/Content/img_icons/parking.png" />
}
</div>
<div class="icon">
#if (#Model.pro_pet == true)
{
<img src="~/Content/img_icons/pet.png" />
}
</div>
<div class="icon">
#if (#Model.pro_smoking == true)
{
<img src="~/Content/img_icons/smoking.png" />
}
</div>
</div>
</div>
</div>
</div>
<div class="user_data">
#if (Convert.ToInt32(Session["user_id"]) == Convert.ToInt32(Model.pro_fk_user))
{
#Html.ActionLink("Close this Ad", "DeleteAd", new { #class = "button", id = Model.pro_id })
}
else
{
<div class="user_data">
<p> Ogłoszenie opublikowane przez: </p>
<div class="data">
<div class="user_photo">
#if (String.IsNullOrEmpty(Model.user_image))
{
<img src="~/Content/img_icons/user.png" />
}
else
{
<img src="#Url.Content(#Model.user_image)" />
}
</div>
<div class="user_info">
<table class="info">
<tr> <td> Użytkownik: </td> <td> #Model.user_name </td></tr>
<tr> <td> Kontakt: </td> <td> #Model.user_contact </td></tr>
<tr> <td> O użytkowniku: </td> <td> #Model.user_description</td></tr>
</table>
<div class="user_icons">
<div class="icon">
#if (Model.user_smoke == true)
{
<img src="~/Content/img_icons/smoking.png" />
}
</div>
<div class="icon">
#if (Model.user_pet == true)
{
<img src="~/Content/img_icons/pet.png" />
}
</div>
</div>
</div>
</div>
</div>
}
</div>
Model
namespace roomie.Models
{
public class Adviewmodel
{
public int pro_id { get; set; }
public string pro_name { get; set; }
public string pro_image { get; set; }
public string pro_address_street { get; set; }
public int pro_address_building_num { get; set; }
public int pro_address_floor { get; set; }
public int pro_price { get; set; }
public string pro_description { get; set; }
public string pro_type { get; set; }
public int pro_room_size { get; set; }
public int pro_room_num { get; set; }
public int pro_bathroom_num { get; set; }
public int pro_roommates { get; set; }
public string pro_room_gender { get; set; }
public bool pro_TV { get; set; }
public bool pro_internet { get; set; }
public bool pro_ac { get; set; }
public bool pro_parking { get; set; }
public string pro_heating { get; set; }
public bool pro_elevator { get; set; }
public bool pro_balcony { get; set; }
public bool pro_handicapped { get; set; }
public bool pro_smoking { get; set; }
public bool pro_pet { get; set; }
public int pro_prefe_gender { get; set; }
public int pro_fk_user { get; set; }
public int user_id { get; set; }
public string user_name { get; set; }
public string user_image { get; set; }
public string user_contact { get; set; }
public string user_description { get; set; }
public bool user_smoke { get; set; }
public bool user_pet { get; set; }
public int pro_fk_address_city { get; set; }
public string nazwa_miasta { get; set; }
public string nazwa_województwa { get; set; }
public IEnumerable<string> pro_img_path { get; set; }
public IEnumerable<string> pro_img_fk_pro_id { get; set; }
}
}
Controller
public ActionResult ViewAd(int id)
{
Adviewmodel ad = new Adviewmodel();
tbl_product p = db.tbl_product.Where(x => x.pro_id == id).SingleOrDefault();
ad.pro_id = p.pro_id;
ad.pro_name = p.pro_name;
//ad.pro_fk_images = p.pro_fk_images;
//ad.pro_fk_address_city = p.pro_fk_address_city;
ad.pro_address_street = p.pro_address_street;
ad.pro_address_building_num = (int)p.pro_address_building_num;
ad.pro_address_floor = (int)p.pro_address_floor;
ad.pro_price = (int)p.pro_price;
ad.pro_description = p.pro_description;
ad.pro_type = p.pro_type;
ad.pro_room_size = (int)p.pro_room_size;
ad.pro_room_num = (int)p.pro_room_num;
ad.pro_roommates = (int)p.pro_roommates;
ad.pro_TV = (bool)p.pro_TV;
ad.pro_internet = (bool)p.pro_internet;
ad.pro_ac = (bool)p.pro_ac;
ad.pro_parking = (bool)p.pro_parking;
ad.pro_heating = p.pro_heating;
ad.pro_elevator = (bool)p.pro_elevator;
ad.pro_balcony = (bool)p.pro_balcony;
ad.pro_handicapped = (bool)p.pro_handicapped;
ad.pro_smoking = (bool)p.pro_smoking;
ad.pro_pet = (bool)p.pro_pet;
//ad.pro_prefe_gender = (int)p.pro_prefe_gender;
tbl_user u = db.tbl_user.Where(x => x.user_id == p.pro_fk_user).SingleOrDefault();
ad.user_name = u.user_name;
ad.user_image = u.user_image;
ad.user_contact = u.user_contact;
ad.pro_fk_user = u.user_id;
tbl_wojewodztwa_miasta wm = db.tbl_wojewodztwa_miasta.Where(x => x.id == p.pro_fk_address_city).SingleOrDefault();
ad.nazwa_miasta = wm.nazwa_miasta;
ad.nazwa_województwa = wm.nazwa_województwa;
ad.pro_img_path = Directory.EnumerateFiles(Server.MapPath("~/ Content / user_upload")).Select(x => "~/ Content / user_upload" + Path.GetFileName(x));
return View(ad);
}
Okay, so i solved my issue, i don't know will it be any help to someone.
In the Model and Controller i added the "?" to the int values that were not required.
Related
Iam getting the following error when posting the form with ProductVM fields:
This is the model being passed:
[BindProperties]
public class ProductVM
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public decimal Price { get; set; }
public int Quantity { get; set; } = 0;
public List<SelectListItem> Categories { get; set; }
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public List<SelectListItem> Suppliers { get; set; }
public int SupplierId { get; set; }
public string SupplierName { get; set; }
}
This is the form:
#model IEnumerable<ProductVM>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.DisplayFor(modelItem => item.CategoryName)
</td>
<form asp-action="AddToCart">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="#item.Id">
<input type="hidden" asp-for="#item.Name">
<input type="hidden" asp-for="#item.Price">
<td>
<input asp-for="#item.Quantity" value="1" class="form-control" style="inline-size:100px">
<span asp-validation-for="#item.Quantity" class="text-danger"></span>
</td>
<td>
<input type="submit" id="addtocart" value="Add To Cart" class="btn btn-primary"/>
</td>
</form>
</tr>
}
Any ideas why the name field is throwing error even with the "input type="hidden" asp-for="#item.Name"" ?
foreach loop is not submiting data back, you have to use for loop
#foreach (var i=0, i< Model.Count; i++) {
.....
<input type="hidden" asp-for="#Model[i].Id">
<input type="hidden" asp-for="#Model[i].Name">
...
}
I have created a view that accepts a ProjectsCreatorsVM class. This class has been structured this way:
public class ProjectsCreatorsVM
{
public List<ProjectVM> ProjectsCreators { get; set; }
public ProjectsCreatorsVM(List<ProjectVM> projectsCreators)
{
ProjectsCreators = projectsCreators;
}
}
In addition, the ProjectVM follow this structure:
public class ProjectVM
{
public Project Project { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public ProjectVM(Project pro, ApplicationUser applUser)
{
Project = pro;
ApplicationUser = applUser;
}
}
Lastly, my view tries to go through the ProjectsCreators.Project but it does not seem to be possible.
<div class="card-content-container" >
#foreach (Project obj in #Model.ProjectsCreators.)
{
<div class="card">
<img class="card-img-top" src="#obj.ImgURL" alt ="project image" >
<div class="card-body d-flex flex-column">
<h5 class="card-title">#obj.Title</h5>
<h6 class="card-title">#obj.Title</h6>
<p class="card-text">
#obj.TruncatedDescription
</p>
<div class="mt-auto" style="display: flex; justify-content: space-between; align-items: center;">
View Details
</div>
</div>
</div>
I would appreciate any help. Thanks in advance.
ProjectCreators is a List and when you iterate ProjectCreators you get a ProjectVM object not a Project or ApplicaionUser instance. If you want to access Project instance add Project after #obj like #obj.Project.Title
<div class="card-content-container" >
#foreach (ProjectVM obj in #Model.ProjectsCreators.)
{
<div class="card">
<img class="card-img-top" src="#obj.Project.ImgURL" alt ="project image" >
<div class="card-body d-flex flex-column">
<h5 class="card-title">#obj.Project.Title</h5>
<h6 class="card-title">#obj.Project.Title</h6>
<p class="card-text">
#obj.Project.TruncatedDescription
</p>
<div class="mt-auto" style="display: flex; justify-content: space-between; align-items: center;">
View Details
</div>
</div>
</div>
}
</div>
To achieve what I wanted, I created another class. That looks like this:
public class ProjectAndUserVM
{
public string ProjectTitle { get; set; }
public string ProjectId { get; set; }
public string ProjectImageUrl { get; set; }
public string ProjectDescription { get; set; }
public string ProjectCreatorName { get; set; }
public string ProjectCreatorId { get; set; }
public string ProjectCreatorEmail { get; set; }
public ProjectAndUserVM(string projectTitle, string projectId, string projectImageUrl, string projectDescription, string projectCreatorName, string projectCreatorId, string projectCreatorEmail)
{
ProjectTitle = projectTitle;
ProjectId = projectId;
ProjectImageUrl = projectImageUrl;
ProjectDescription = projectDescription;
ProjectCreatorName = projectCreatorName;
ProjectCreatorId = projectCreatorId;
ProjectCreatorEmail = projectCreatorEmail;
}
}
So, basically my controller is returning that as a list which I convert to an IEnumerable. and I use that list on my view instead.
i have selectList with multiple attr which is filled through cascading(on select a company i just show selected Company Models) Now i want to allow user to select multiple models such that on select, item should add in c# list and display in page and then allow user to select more of any other company.Picture attached
Following is my code.
OrderViewModel
public class OrderViewModel
{
[Display(Name ="Order ID")]
public int order_id { get; set; }
[Required]
public string cus_name { get; set; }
public string cus_phone { get; set; }
public System.DateTime Date { get; set; }
[DataType(DataType.Date)]
public System.DateTime Date { get; set; }
public int Amount { get; set; }
public List<Products> Products { get; set; }
}
i want to bind selected Item in 'Products' List of OrderViewModel which will be send to server with Further fields.
Products
public class Products
{
public int id { get; set; }
public int modelId { get; set; }
public int Phoneid { get; set; }
public int Quantity { get; set; }
public double price { get; set; }
public bool isSelected { get; set; }
public int order_id { get; set; }
}
Razor View
<div class="form-group row">
<label class="control-label col-6">Company Name</label>
<div class="col-12">
<select id="CompanyId" class="custom-select mr-sm-2"
asp-items="#(new SelectList( #ViewBag.Companies,"Phoneid","Com_name"))">
<option value="">Please Select</option>
</select>
</div>
<span class="text-danger"></span>
</div>
<div class="form-group row">
<label class="control-label col-6"></label>
<div class="col-12">
<select id="modelId" multiple class="custom-select mr-sm-2"
asp-items="#(new SelectList(string.Empty,"modelId","model_name","--Select--"))">
<option value="">Please Select</option>
</select>
</div>
<span class="text-danger"></span>
</div>
what i have tried yet to add item in list
<script>
$("#modelId").change(function () {
var list = #(Model.Products);
let item = $(this).children("option:selected").val();
list.forEach(x => {
if (x.modelId != item) {
#{
Products products = new Products()
{
isSelected=true,
modelId= item,
};
Model.Products.Add(products);
}
}
});
})
#for (int i = 0; i < Model.Products.Count; i++)
{
}
</script>
I display all selected product throught partial view now i just want to send these selected products along with Quanity and Price of each to Server
Here is a working demo like below:
Model:
public class Model
{
[Key]
public int modelId { get; set; }
[Display(Name = "Model Name")]
public string model_name { get; set; }
public int Phoneid { get; set; }
public IList<Products> Products { get; set; }
}
public class Company
{
[Key]
public int Phoneid { get; set; }
[Display(Name = "Company Name")]
public string Com_name { get; set; }
}
public class Products
{
public int id { get; set; }
public int modelId { get; set; }
public int Phoneid { get; set; }
public int Quantity { get; set; }
public double price { get; set; }
public bool isSelected { get; set; }
public int order_id { get; set; }
}
View(Index.cshtml):
#model Products
<div>
<div style="float:left;width:40%">
<form id="form">
<div class="form-group row">
<label>Company Name</label>
<div class="col-12">
<select id="CompanyId" asp-for="Phoneid" class="custom-select mr-sm-2"
asp-items="#(new SelectList( #ViewBag.Companies,"Phoneid","Com_name"))">
<option value="">Please Select</option>
</select>
</div>
</div>
<div class="form-group row">
<label>Model Name</label>
<div class="col-12">
<select id="modelId" multiple class="custom-select mr-sm-2" name="modelId"
asp-items="#(new SelectList(string.Empty,"modelId","model_name","--Select--"))">
<option value="">Please Select</option>
</select>
</div>
</div>
<div>
<input type="button" id="saveBtn" value="Save" />
</div>
</form>
</div>
<div style="float:right;width:60%">
<h5>Products</h5>
<div id="products"></div>
</div>
</div>
#section Scripts
{
<script>
$(function () {
$('#CompanyId').change(function () {
var data = $("#CompanyId").val();
console.log(data);
$.ajax({
url: '/Home/GetModel?Phoneid=' + $("#CompanyId").val(),
type: 'Get',
success: function (data) {
var items = "<option value='0'>Select</option>";
$.each(data, function (i, item) {
items += "<option value='" + item.value + "'>" + item.text + "</option>";
});
$('#modelId').html(items);
}
})
});
$('#saveBtn').click(function () {
$.ajax({
url: '/Home/GetProduct?Phoneid=' + $("#CompanyId").val() + "&modelId=" + $('#modelId').val(),
type: 'Post',
success: function (data) {
$('#products').html(data);
}
})
})
})
</script>
}
Partial View(_Partial.cshtml):
#model IEnumerable<Products>
<table class="table">
<tbody>
#foreach (var item in Model)
{
<tr>
<td>check</td>
<td>
<input asp-for="#item.isSelected" />
</td>
<td>Product Id</td>
<td>
#Html.DisplayFor(modelItem => item.id)
</td>
</tr>
<tr>
<td>Quantity</td>
<td>
#Html.DisplayFor(modelItem => item.Quantity)
</td>
<td>Price</td>
<td>
#Html.DisplayFor(modelItem => item.price)
</td>
</tr>
}
</tbody>
</table>
Controller:
public class HomeController : Controller
{
private readonly MvcProj3Context _context;
public HomeController(MvcProj3Context context)
{
_context = context;
}
public IActionResult Index()
{
ViewBag.Companies = _context.Company.ToList();
return View();
}
public JsonResult GetModel(int Phoneid)
{
List<Model> model = new List<Model>();
model = (from m in _context.Model
where m.Phoneid == Phoneid
select m).ToList();
return Json(new SelectList(model, "modelId", "model_name"));
}
[HttpPost]
public IActionResult GetProduct(int Phoneid, string[] modelId)
{
var data = new List<Products>();
var ids = modelId[0].Split(',');
foreach(var item in ids)
{
var id = int.Parse(item);
//guess the modelA in CompanyA contains several products
var product = (from p in _context.Products
where p.Phoneid == Phoneid && p.modelId == id
select p).ToList();
foreach (var pro in product)
{
data.Add(pro);
}
}
return PartialView("_Partial", data);
}
}
Result:
The error shows as below:
System.Web.HttpCompileException:
'C:\Users\MEDADUWA\source\repos\CapeXPro\CapeXPro\Views\FAWizard_AddAsset.cshtml(43):
error CS1579: foreach statement cannot operate on variables of type
'FAInfo' because 'FAInfo' does not contain a public definition for
'GetEnumerator''
My ViewModel Look like this:
namespace DAL.Entities
{
public class FAInfo
{
public int WizardId { get; set; }
public string WizardType { get; set; }
public Step2 Step2 { get; set; }
public List<Step2> ListStep2 { get; set; }
public int Status { get; set; }
}
public class Step2
{
public int assetId { get; set; }
public string assetCode { get; set; }
public int assetCategoryId { get; set; }
public int assetTypeId { get; set; }
public int branchId { get; set; }
public int? ccenterId { get; set; }
public string description { get; set; }
public double cost { get; set; }
public double? vat { get; set; }
public double? vatRec { get; set; }
public double? nbt { get; set; }
public double bookValue { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime? ModifiedOn { get; set; }
public string ModifiedBy { get; set; }
public int Status { get; set; }
public InvoiceEntities Invoice { get; set; }
public List<Step2> ListAssets { get; set; }
public List<tbl_assetcategory> ListCategories { get; set; }
public List<tbl_branch> ListBranches { get; set; }
public List<tbl_costcenter> ListDepartments { get; set; }
}
}
This is my Controller:
namespace CapeXPro.Controllers
{
[SessionExpire]
public class FAWizardController : Controller
{
UnitOfWork _unitOfWork = new UnitOfWork();
readonly CommonUtilities _commonService = new CommonUtilities();
#region Main View
FAInfo FAInfoComponent(FAInfo model = null)
{
try
{
//var existjournaldepreciation = _unitOfWork.JournalDepreciationRepository.GetAll(x => x.Id == 1 && x.Status != (int)StatusEnum.Delete).FirstOrDefault();
if (model == null)
{
model = new FAInfo()
{
Status = (int)StatusEnum.Active,
};
}
return model;
}
catch (Exception ex)
{
throw ex;
}
}
// GET: FAWizard
public ActionResult FAWizard()
{
return View("FAWizard", FAInfoComponent());
}
#endregion
#region Add Or Edit Step2
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Step2(FAInfo AssetData, string BtnPrevious, string BtnNext)
{
try
{
var action = string.Empty;
var before = string.Empty;
var after = string.Empty;
AssetData = FAInfoComponent(AssetData);
if (BtnPrevious != null)
{
FAInfo InvObj = new FAInfo();
InvObj.Step1.InvoiceId = AssetData.Step2.Invoice.InvoiceId;
InvObj.Step1.InvoiceNo = AssetData.Step2.Invoice.InvoiceNo;
InvObj.Step1.PoNo = AssetData.Step2.Invoice.PoNo;
return PartialView("_AddInvoice", InvObj);
}
if (BtnNext != null)
{
if (ModelState.IsValid)
{
var existObj = _unitOfWork.AssetRepository.GetAll(x => x.assetId == AssetData.Step2.assetId && x.Status != (int)StatusEnum.Delete).FirstOrDefault();
if (existObj == null)
{
tbl_asset asset = new tbl_asset()
{
assetId = AssetData.Step2.assetId,
assetCode = AssetData.Step2.assetCode,
assetCategoryId = AssetData.Step2.assetCategoryId,
CreatedBy = System.Web.HttpContext.Current.Session[SessionsEnum.UserId.ToString()].ToString(),
CreatedOn = DateTime.Now,
Status = Convert.ToInt32(AssetData.Status)
};
_unitOfWork.AssetRepository.Insert(asset);
//_unitOfWork.Save();
//int id = department.CcId;
action = ActionType.Insert;
before = null;
after = asset.assetId + "," +
asset.assetCode + "," +
asset.assetCategoryId + "," +
asset.Status + "," +
asset.CreatedBy + "," +
asset.CreatedOn + "," +
asset.ModifiedBy + "," +
asset.ModifiedOn;
}
else
{
FAInfo AssetObj = new FAInfo();
AssetObj.Step2.assetId = AssetData.Step2.assetId;
AssetObj.Step2.assetCode = AssetData.Step2.assetCode;
AssetObj.Step2.assetCategoryId = AssetData.Step2.assetCategoryId;
AssetObj.Step2.ModifiedBy = System.Web.HttpContext.Current.Session[SessionsEnum.UserId.ToString()].ToString();
AssetObj.Step2.ModifiedOn = DateTime.Now;
AssetObj.Step2.Status = Convert.ToInt32(AssetData.Status);
_unitOfWork.AssetRepository.Update(existObj);
action = ActionType.Update;
before = null;
after = existObj.assetId + "," +
existObj.assetCode + "," +
existObj.assetCategoryId + "," +
existObj.Status + "," +
existObj.CreatedBy + "," +
existObj.CreatedOn + "," +
existObj.ModifiedBy + "," +
existObj.ModifiedOn;
}
if (_unitOfWork.Save() > 0)
{
//Update Log Table
AuditLog.SystemLog(Tables.AssetTable, action, before, after);
TempData["message"] = Messages.Success;
ModelState.Clear();
return View("AddDepreciation", new FADepreciationEntities());
}
else
{
TempData["message"] = Messages.Failed;
return PartialView("_AddAsset", AssetData);
}
}
return PartialView("_AddAsset", AssetData);
}
return View();
}
catch (Exception ex)
{
TempData["message"] = Messages.Exception + ex.Message;
return PartialView("_AddAsset", AssetData);
}
}
#endregion
}
}
This is my Partial View
#model DAL.Entities.FAInfo
#using DAL.Enums
#using (Html.BeginForm("Step2", "FAWizard", FormMethod.Post, new { #class = "form-horizontal form-label-left", role = "form", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(m => m.Step2.assetId)
<!-- Editable table -->
<div class="card">
<div class="card-body">
<div id="table" class="table-editable">
<span class="table-add float-right mb-3 mr-2">
<a href="#!" class="text-success">
<i class="fas fa-plus fa-2x" aria-hidden="true"></i>
</a>
</span>
<table id=""
class="table table-striped table-hover table-sm table-bordered text-center">
<thead>
<tr>
<th class="text-center">Line No</th>
<th class="text-center">Asset Code</th>
<th class="text-center">Asset Class</th>
</tr>
</thead>
<tbody>
#foreach (DAL.Entities.FAInfo asset in Model)
{
<tr>
<td>1</td>
<td>#asset.Step2.assetCode</td>
<td>#asset.Step2.ListCategories</td>
<td>
<span class="table-remove">
<button type="button"
class="btn btn-danger btn-rounded btn-sm my-0">
Remove
</button>
</span>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
}
This is my MasterView:
#model DAL.Entities.FAInfo
#using DAL.Enums
#{
ViewBag.Title = "FAWizard";
}
<div class="right_col" role="main">
<div class="full-height">
<div class="clearfix"></div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2>Fixed Assets Capitalization <small>CapeXPro</small></h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<form class="form-horizontal form-label-left" novalidate>
<p>
For Fixed asset registration - CapeXPro | Union Bank of Colombo
</p>
<span class="section">Fixed Asset Info</span>
<!-- Smart Wizard -->
<p>Proceed with the given steps</p>
<div id="wizard" class="form_wizard wizard_horizontal">
<ul class="wizard_steps">
<li>
<a href="#step-1">
<span class="step_no">1</span>
<span class="step_descr">
Step 1<br />
<small>Invoice and Insurance Details</small>
</span>
</a>
</li>
<li>
<a href="#step-2">
<span class="step_no">2</span>
<span class="step_descr">
Step 2<br />
<small>Asset Details</small>
</span>
</a>
</li>
</ul>
<div id="step-1">
#{Html.RenderPartial("_AddInvoice", Model);}
</div>
<div id="step-2">
#{Html.RenderPartial("_AddAsset", Model);}
</div>
</div>
<!-- End SmartWizard Content -->
</form>
</div>
</div>
</div>
</div>
</div>
</div>
System.Web.HttpCompileException: 'C:\Users\MEDADUWA\source\repos\CapeXPro\CapeXPro\Views\FAWizard_AddAsset.cshtml(43): error CS1579: foreach statement cannot operate on variables of type 'FAInfo' because 'FAInfo' does not contain a public definition for 'GetEnumerator''
This error is thrown because in your partial view FAWizard_AddAsset you're trying to iterate your model like this #foreach (DAL.Entities.FAInfo asset in Model). This assumes that Model is an enumerable of FAInfo, like a List<FAInfo> but apparently it's a FAInfo.
Judging by your code I think there's no multiples of FAInfo, but within your FAInfo there's a List<ListStep2>. If you want to iterate that then change your #foreach into this:
#foreach (DAL.Entities.Step2 asset in Model.ListStep2)
In your #model statement you are using a single instance. This is useful for Details and Edit views of single items. To iterate over entities in a view, you can make the model an IEnumerable of MyClass like so:
#model IEnumerable<DAL.Entities.FAInfo>
CustomCssFields is null when going back to controller. I already set a constructor but it is still the same. I found some similar question MVC Model with a list of objects as property but it almost has the same code as mine.
MODEL
public class CompanyModelView
{
public CompanyModelView()
{
CustomCssFields = new List<CompanyCssReferenceModelView>();
}
[BsonId]
public string _id { get; set; }
[BsonElement("CompanyName")]
[DisplayName("Company Name")]
public string CompanyName { get; set; }
[BsonElement("CompanyCode")]
[DisplayName("Company Code")]
public string CompanyCode { get; set; }
[BsonElement("CompanyConnectionString")]
[DisplayName("Company Connection String")]
public string CompanyConnectionString { get; set; }
[BsonElement("CargowiseVersion")]
[DisplayName("Cargowise Version")]
public string CargoWiseVersion { get; set; }
[BsonElement("CustomCssFields")]
[UIHint("CustomCssFields")]
public IList<CompanyCssReferenceModelView> CustomCssFields { get; set; }
}
public class CompanyCssReferenceModelView
{
[BsonElement("FieldName")]
public CssOptionEnum FieldName;
[BsonElement("FieldValue")]
public string FieldValue;
}
VIEW
here is the view.
#model WebTrackerModels.CompanyModels.CompanyModelView
<form asp-action="SaveCompany" enctype="multipart/form-data">
<div class="form-group">
<table class="table">
<thead>
<tr>
<th>
Field Name
</th>
<th>
Field Value
</th>
</tr>
</thead>
<tbody>
#{
for (int i = 0; i < Model.CustomCssFields.Count; i++)
{
<tr>
<td>
#Html.DisplayFor(model => model.CustomCssFields[i].FieldName)
</td>
<td>
#Html.TextBoxFor(model => model.CustomCssFields[i].FieldValue, new { #class = "form-control", type = "color", value = Model.CustomCssFields[i].FieldValue })
</td>
</tr>
}
}
</tbody>
</table>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-success" />
</div>
</form>