I have a View that contains an Model, this model contains a list(of another Model) and this list is filled in my view with Dynamic repeating fields;
Model:
public class CAOEntry
{
public CAOEntry()
{
this.TimeEntries = new List<TimeEntry>() { new TimeEntry() };
}
public DateTime ValidFrom { get; set; }
public DateTime ValidTo { get; set; }
public List<TimeEntry> TimeEntries {get; set;}
}
My View(the part that creates the handles the TimeEntry List)
#Html.EditorFor(model => model.TimeEntries)
<button data-bind="click: addTimeEntry">Voeg tijdsvak toe</button>
<button data-bind="click: removeTimeEntry">Verwijder laatste</button>:
the data-bind"click:addTimeEntry" is a jQuery/KnockoutJs script that adds new time entries. These are added from an Editor Template.
In this Editor template i got the following line of code:
#Html.EnumDropDownListFor(model => model.DayOfWeekOrHoliday,"--Selecteer een dag--", new { htmlAttributes = new { #class = "form-control", data_bind = "value: DayOfWeekOrHoliday, namePath: true" } })
Now the following happens when i have, for example two, TimeEntries filled in and click on save;
There are three time entries returned to my controller:
One containing the first filled Enum Value, other fields are null.
the other two don't contain any Enum values but have the other fields filled.
When debugging the view, i saw the following problem;
TimeEntry 1:
enum field;
id="TimeEntries_0__DayOfWeekOrHoliday" name="TimeEntries[0].DayOfWeekOrHoliday"
Example of a second field:
id="TimeEntries_1__TimeFrom" name="TimeEntries[1].TimeFrom"
TimeEntry 2:
Enum field;
id="TimeEntries_0__DayOfWeekOrHoliday" name="TimeEntries[0].DayOfWeekOrHoliday"
Example of a second field:
id="TimeEntries_2__TimeFrom" name="TimeEntries[2].TimeFrom"
so the Array is not incremented right for the enum value. Is this because there is an enum field in an EditorFor helper?
I can't figure out how to solve this.
[Edit]
TimeEntry Class:
public class TimeEntry
{
public int ID { get; set; }
//1:Monday,2:Tuesday,3:Wednesday,4:Thursday,5:Friday,6:Saturday,7:Sunday,8:Any Holiday
public enum Days {Maandag =1,Dinsdag =2, Woensdag=3,Donderdag = 4, Vrijdag= 5, Zaterdag=6, Zondag=7, Feestdag = 8}
[Required]
[Display(Name = "Dag")]
[Range(1, int.MaxValue, ErrorMessage = "Selecteer een dag")]
public Days DayOfWeekOrHoliday { get; set; }
[Required]
[Display(Name = "Start Tijdvak(uur:minuten)")]
[StringLength(5, MinimumLength = 5)]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh:mm}")]
public string TimeFrom { get; set; }
[Required]
[Display(Name = "Eind Tijdvak(uur:minuten)")]
[StringLength(5, MinimumLength = 5)]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh:mm}")]
public string TimeTo { get; set; }
[Required]
public decimal Premium { get; set; }
}
EditorFor:
function createViewModel() {
var createTimeEntry = function () {
return {
DayOfWeekOrHoliday: ko.observable(),
TimeFrom: ko.observable(),
TimeTo: ko.observable(),
Premium: ko.observable()
};
};
var addTimeEntry = function () {
TimeEntries.push(createTimeEntry());
};
var removeTimeEntry = function () {
TimeEntries.pop();
};
var ValidFrom = ko.observable();
var ValidTo = ko.observable();
var TimeEntries = ko.observableArray([createTimeEntry()]);
return {
ValidFrom: ValidFrom,
ValidTo: ValidTo,
TimeEntries: TimeEntries,
addTimeEntry: addTimeEntry,
removeTimeEntry: removeTimeEntry
};
}
$(document).ready(function () {
var viewModel = createViewModel();
ko.applyBindings(viewModel);
});
</script>
Related
I am trying to update data from two tables; products and inventory. The main key of the table products is cod_prod, which is the barcode of a product. This is the relationship with the products table and the other. The update is carried out for all the fields, but in the database administrator, the cod_prod field in the inventory table is not updated, it only becomes null, in the products table the update is carried out, the reg_date field, which is a field in the inventory table is also updated. Only the cod_prod field on the inventory table is not updated and I don't know why.
ViewModel:
public class products
{
[Display(Name = "Name")]
public string name { get; set; }
[Key]
[Display(Name = "Product Code")]
public string cod_prod { get; set; }
[Display(Name = "Register Date")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? reg_date { get; set; }
}
Controller:
[HttpGet]
public ActionResult prodEdit(int id)
{
using (inventarioEntitiesDBA dc = new inventarioEntitiesDBA())
{
var u = dc.products.Where(a => a.id == id).FirstOrDefault();
if (u != null)
{
var pm = new products
{
name = u.name,
cod_prod = u.cod_prod,
reg_date = u.reg_date
};
var b = dc.inventory.Where(x => x.cod_prod == pm.cod_prod).FirstOrDefault();
u.cod_prod = b.cod_prod;
return View(u);
}
return Content("Invalid Request");
}
}
[HttpPost]
public ActionResult prodEdit(products prod)
{
using (inventarioEntitiesDBA dc = new inventarioEntitiesDBA())
{
var u = dc.products.Where(a => a.id == prod.id).FirstOrDefault();
var b = dc.inventory.Where(x => x.cod_prod == prod.cod_prod).FirstOrDefault();
inventory bod = new inventory()
{
cod_prod = prod.cod_prod,
reg_date = prod.reg_date
};
dc.inventory.Remove(b);
dc.inventory.Add(bod);
dc.products.Remove(u);
dc.products.Add(prod);
dc.SaveChanges();
return RedirectToAction("prodList", "products");
}
}
Any suggestion is appreciated.
UPDATE:
Model for products:
public partial class products
{
[Display(Name = "Name")]
public string name { get; set; }
[Key]
[Display(Name = "Product Code")]
public string cod_prod { get; set; }
}
Model for inventory:
public partial class inventory
{
[Key]
[Display(Name = "Product Code")]
public string cod_prod { get; set; }
[Display(Name = "Register Date")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? reg_date { get; set; }
}
Suppose you have one to one relation between Products and Inventory tables, your models will look like this in EF:
Products model
public class Products
{
[Display(Name = "Name")]
public string name { get; set; }
[Key]
[Display(Name = "Product Code")]
public string cod_prod { get; set; }
public virtual Inventory Inventory {get;set;}
}
Inventory model
public class Inventory
{
[Key, ForeignKey("Products")]
[Display(Name = "Product Code")]
public string cod_prod { get; set; }
[Display(Name = "Register Date")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? reg_date { get; set; }
public virtual Products Products {get;set;}
}
Once relation is configured, you can simply do this in the POST method to update product and inventory:
[HttpPost]
public ActionResult prodEdit(Products prod)
{
using (inventarioEntitiesDBA dc = new inventarioEntitiesDBA())
{
var product = dc.products.Where(a => a.id == prod.id).FirstOrDefault();
var inventory = product.Inventory;
inventory.cod_prod = prod.cod_prod;
inventory.reg_date = prod.reg_date;
dc.SaveChanges();
return RedirectToAction("prodList", "products");
}
}
You can read more about how to configure EF relation here.
If the same thing happens to someone, this is what I wrote to resolve it, the controller has two post methods, the first removes the fields that were changed, save data base and send the products and inventory objects to the second method, there, adds the new data of the models and save. I had to do this way because the removal of the PK on the products table causes the null thing.
Controller:
[HttpPost]
public ActionResult prodEdit(products prod)
{
using(inventarioEntitiesDBA dc = new inventarioEntitiesDBA())
{
var u = dc.products.Where(a => a.id == prod.id).FirstOrDefault();
if(u != null)
{
var pm = new products
{
prod_name = prod.prod_name,
cod_prod = prod.cod_prod,
fecha_ingreso = prod.fecha_ingreso
};
var b = dc.bodega.Where(x => x.cod_prod == u.cod_prod).FirstOrDefault();
if (b != null)
{
inventory inv = new inventory()
{
reg_date = pm.fecha_ingreso,
cod_prod = pm.codigo_prod
};
if (inv.cod_prod != null)
{
dc.inventory.Remove(b);
dc.products.Remove(u);
dc.SaveChanges();
prodEdit2(prod, bod);
}
}
}
return RedirectToAction("prodList", "products");
}
}
[HttpPost]
public ActionResult prodEdit2(products p, inventory i)
{
using (inventarioEntitiesDBA dc = new inventarioEntitiesDBA())
{
dc.products.Add(p);
dc.inventory.Add(i);
dc.SaveChanges();
return RedirectToAction("prodList", "products");
}
}
The context of application the is maintaining security orders from Investment Advisors. On a screen where an users amends his orders is the problem appears. In such screen a I have dropdown list to specify the order type whether its a buy or sell and shows values for security, Quantity and price.
Problem
I have witnessed while being in an Edit screen, after doing an amendment (Tests have performed not by changing the Buy/Sell but others i.e price). If I performed a HTTP Post, the values of the DropDownList returns null. Refer screenshot:
Initialization of SelectList type
public static List<SelectListItem> getBuySellList()
{
List<SelectListItem> buySell = new List<SelectListItem>();
SelectListItem item;
item = new SelectListItem();
item.Text = "BUY";
item.Value = "BUY";
buySell.Add(item);
item = new SelectListItem();
item.Text = "SELL";
item.Value = "SELL";
buySell.Add(item);
return buySell;
}
My Controller as follows:
// GET: OrderFlow/Edit/5
public ActionResult Edit(int id)
{
OrderFlowModel orderFlowModel = db.Find(id);
ViewData["ORDERFLOW_NO"] = id;
ViewBag.OrderFlowBuySell = Utility.UtilityDBContext.getBuySellList();
return View(orderFlowModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(string OrderFlowNo, string OrderFlowSecurityID, string OrderFlowBuySell, string OrderFlowQuantity, string OrderFlowPrice, string OrderFlowTradingDate, string OrderFlowClientAccount, string OrderFlowParticipant, string OrderFlowBuyStatus)
{
if (ModelState.IsValid)
{
OrderFlowModel orderFlowModel = new OrderFlowModel();
orderFlowModel.OrderFlowNo = int.Parse(OrderFlowNo.ToString());
orderFlowModel.EquityID = OrderFlowSecurityID;
orderFlowModel.BuySell = OrderFlowBuySell;
orderFlowModel.Quantity = int.Parse(OrderFlowQuantity);
orderFlowModel.Price = double.Parse(OrderFlowPrice);
DateTime dt;
if (DateTime.TryParseExact(OrderFlowTradingDate, formats, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
orderFlowModel.TradingDate = dt;
}
else orderFlowModel.TradingDate = DateTime.Today;
orderFlowModel.ClientAccountID = OrderFlowClientAccount;
orderFlowModel.ParticipantAccountID = OrderFlowParticipant;
orderFlowModel.Status = OrderFlowBuyStatus;
try
{
db.Edit(orderFlowModel);
return RedirectToAction("Index");
}
catch (Exception er)
{
TempData["Message"] = er.Message;
}
}
ViewBag.OrderFlowBuySell = Utility.UtilityDBContext.getBuySellList();
return RedirectToAction("Edit", new{id=OrderFlowNo});
}
The OrderFlow Model:
public class OrderFlowModel
{
[Display(Name = "Order Flow No")]
public int OrderFlowNo { get; set; }
[Display(Name = "Valid Till")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
[DataType(DataType.Date)]
public DateTime TradingDate { get; set; }
[Display(Name = "Client A/c ID")]
public string ClientAccountID { get; set; }
[Display(Name = "Participant ID")]
public string ParticipantAccountID { get; set; }
[Required(ErrorMessage="Security is Required")]
[Display(Name = "Security")]
public string EquityID { get; set; }
[Required(ErrorMessage = "Buy or Sell Needs to specify")]
[Display(Name = "BS")]
public string BuySell { get; set; }
[DefaultSettingValue("0")]
[Display(Name = "Quantity")]
[DisplayFormat(DataFormatString = "{0:N0}")]
public int Quantity { get; set; }
[Display(Name = "Price")]
[DataType(DataType.Currency)]
[DisplayFormat(DataFormatString = "{0:N2}")]
public double Price { get; set; }
[Display(Name = "Status")]
public string Status { get; set; }
[Display(Name = "User Entered")]
public string UserEntered { get; set; }
[Display(Name = "Effective From")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime EffectiveStart { get; set; }
[Display(Name = "Effective Till")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime EffectiveEnd { get; set; }
}
The way I have assigned DropdownListFor in Razor as follows:
#Html.DropDownListFor(model => model.BuySell, new SelectList(ViewBag.OrderFlowBuySell, "Text", "Value"), new { #id = "OrderFlowBuySell", #class = "form-control" })
HTML output from Browser for the Dropdown List
<select class="form-control" data-val="true" data-val-required="Buy or Sell Needs to specify" id="OrderFlowBuySell" name="BuySell"><option selected="selected" value="BUY">BUY</option>
<option value="SELL">SELL</option>
</select>
The value that needs to be in your controller method is BuySell, this is the selected id of the dropdownlist from your mark-up below (the first parameter):
#Html.DropDownListFor(model => model.BuySell,
new SelectList(ViewBag.OrderFlowBuySell, "Text", "Value"),
new { #id = "OrderFlowBuySell", #class = "form-control" })
The OrderFlowBuySell is the collection of options that are used to bind the dropdown, in the post you are usually only concerned with the option a user has selected.
Change it to this and the value will be posted:
Edit(string OrderFlowNo, string OrderFlowSecurityID,
string OrderFlowBuySell, string OrderFlowQuantity,
string OrderFlowPrice, string OrderFlowTradingDate,
string OrderFlowClientAccount, string OrderFlowParticipant,
string OrderFlowBuyStatus, string BuySell)
However I would strongly advise you use ViewModels, that way you can just speficy a single object to your controller post.
I have a Create page that have a Dropdownlist with Players
This I populate in my controller
[HttpGet]
public ActionResult Create()
{
var vm = new CreateMatchViewModel
{
Winner =
CreateWinnerList(),
PlayerList = CreatePlayerList()
}
;
return View(vm);
}
private IEnumerable<SelectListItem> CreatePlayerList()
{
List<Player> playerList = _playerManagementRepository.GetAllPlayers();
return playerList.Select(p => new SelectListItem
{
Text = p.Username,
Value = p.Id.ToString()
});
}
private SelectListItem[] CreateWinnerList()
{
return new[]
{
new SelectListItem {Text = "Player 1", Value = 1.ToString(), Selected = true}
, new SelectListItem {Text = "Player 2", Value = 2.ToString(), Selected = false}
};
}
This populates my view fine
#model TableTennis.ViewModels.CreateMatchViewModel
#{
ViewBag.Title = "Enter Match Result";
}
#using (Html.BeginForm("Create", "Match", FormMethod.Post))
{
<h4>Player 1</h4>
#Html.DropDownListFor(p => p.Player1ID, Model.PlayerList)
<h4>Player 2</h4>
#Html.DropDownListFor(p => p.Player2ID, Model.PlayerList)
<h4>Winner</h4>
#Html.DropDownListFor(w => w.WinnerID, Model.Winner)
<h5>Set 1</h5>
#Html.EditorFor(p => p.Score1Set1)
#Html.EditorFor(p => p.Score2Set1)
<h5>Set 2</h5>
#Html.EditorFor(p => p.Score1Set2)
#Html.EditorFor(p => p.Score2Set2)
<h5>Set 3</h5>
#Html.EditorFor(p => p.Score1Set3)
#Html.EditorFor(p => p.Score2Set3)
<input type="submit" value="Add result" />
}
Then on Post I do some validation where ModelState is not valid, so the following is run
[HttpPost]
public ActionResult Create(CreateMatchViewModel vm)
{
try
{
if (!ModelState.IsValid)
{
vm.PlayerList = CreatePlayerList();
vm.Winner = CreateWinnerList();
return View(vm);
}
But this fails follwing error, but I am not sure how to cast the Guid to a SelectedListItem so that the same item in the list is selected again on the new Get request
The ViewData item that has the key 'Player1ID' is of type 'System.Guid' but must be of type 'IEnumerable'.
ViewModel
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace TableTennis.ViewModels
{
public class CreateMatchViewModel
{
public CreateMatchViewModel()
{
Score1Set1 = 0;
Score1Set2 = 0;
Score1Set3 = 0;
Score2Set1 = 0;
Score2Set2 = 0;
Score2Set3 = 0;
}
public IEnumerable<SelectListItem> PlayerList { get; set; }
public IEnumerable<SelectListItem> Winner { get; set; }
[Required]
public Guid Player1ID { get; set; }
[Required]
public Guid Player2ID { get; set; }
[Required]
public int WinnerID { get; set; }
[Required]
[RegularExpression("[0-9][0-9]?")]
public int Score1Set1 { get; set; }
[RegularExpression("[0-9][0-9]?")]
[Required]
public int Score1Set2 { get; set; }
[RegularExpression("[0-9][0-9]?")]
[Required]
public int Score1Set3 { get; set; }
[RegularExpression("[0-9][0-9]?")]
[Required]
public int Score2Set1 { get; set; }
[RegularExpression("[0-9][0-9]?")]
[Required]
public int Score2Set2 { get; set; }
[RegularExpression("[0-9][0-9]?")]
[Required]
public int Score2Set3 { get; set; }
}
}
EDIT
This made it work
if (!ModelState.IsValid)
{
ModelState.Clear();
vm.PlayerList = CreatePlayerList();
vm.Winner = CreateWinnerList();
return View(vm);
}
if (vm.Player1ID == vm.Player2ID)
{
ModelState.Clear();
vm.PlayerList = CreatePlayerList();
vm.Winner = CreateWinnerList();
return View(vm);
}
Original answer:
Problem is that in your CreatePlayerList() method you are casting the id to a string so MVC is unable to get the selected item based on the id in your model, which is a guid. Player1ID and Player2ID need to be strings in your ViewModel, no matter what you do with them in your database.
Actual answer, fished out of the comments:
The problem, despite the text of the error message is NOT that Player1ID needs to be IEnumerable or IEnumerable but that the list is gone from the model, or the list does not contain the ID. You (may) need to examine the ViewModel when ModelState is not valid and determine what is not valid and why. You may have to use ModelState.Remove() along with reconstructing what is faulty in your Model.
I have this problem where i want to make 7 dropdowns for each day of the week.
In each one of those dropdowns i wish to add the same data.
My ViewModel:
public class WeekDienstCreateViewModel
{
public WeekDienst weekDienst {get; set;}
public List<DienstPerWeekDienst> diensten { get; set; }
public WeekDienstCreateViewModel() { }
}
My Create Method in Controller:
As u can see I add everything allready except DienstId which is want to add with my dropdowns.
public ActionResult Create(int id)
{
WeekDienst wd = _service.FindWeekDienst(id);
WeekDienstCreateViewModel vm = new WeekDienstCreateViewModel();
vm.diensten = new List<DienstPerWeekDienst>();
vm.weekDienst = wd;
for (int i = 1; i <= 7; i++)
{
DienstPerWeekDienst dpwd = new DienstPerWeekDienst();
dpwd.volgnummer = i;
dpwd.WeekDienstId = wd.Id;
vm.diensten.Add(dpwd);
}
ViewBag.Diensten = _service.DienstenList(wd.AfdelingId);
return View(vm);
}
Classes:
public class DienstPerWeekDienst
{
[Key]
public int Id { get; set; }
[Required]
public int WeekDienstId { get; set; }
[Required]
public int DienstId { get; set; }
[Required]
[Range(1, 7)]
public int volgnummer { get; set; }
[ForeignKey("WeekDienstId")]
public virtual WeekDienst WeekDienst { get; set; }
[ForeignKey("DienstId")]
public virtual Dienst Dienst { get; set; }
public virtual ICollection<WeekDienst> WeekDiensten { get; set; }
}
public class WeekDienst
{
[Key]
public int Id { get; set; }
[Required]
public int AfdelingId { get; set; }
[Required]
[StringLength(5, ErrorMessage = "Value for {0} cannot exceed {1} characters.")]
[RegularExpression(#"^[a-zA-Z0-9]{5}$", ErrorMessage = "Verplicht 5 cijfers lang.")]
public string code { get; set; }
[DisplayName("Template")]
public bool template { get; set; }
[ForeignKey("AfdelingId")]
public virtual Afdeling Afdeling { get; set; }
}
And in my view i wish to create 7 dropdowns where i put in all my "Diensten" (class Dienst, fk in DienstPerWeekDienst). When I choose 1 i wish to add the "DienstId" into the "DienstPerWeekDienst" class.
So in my View i got this:
#foreach (var day in Model.diensten)
{
var currentDay=day;
#Html.DropDownListFor(currentDropDown=>currentDay, new SelectList(ViewBag.Diensten, "Value", "Text"))
}
I Wish to postback the chosen "Diensten" and create the "WeekDienst" but now i am just posting a null "DienstPerDienstWeekCreateViewModel". How am I able to fix this?
Thanks in Advance
FIX (Thanks to Siva Gopal)
I fixed this by doing:
#for (int i = 0; i < #Model.diensten.Count; i++)
{
#Html.HiddenFor(m => (m.diensten[i].volgnummer))
#Html.HiddenFor(m => (m.diensten[i].WeekDienstId))
#Html.DropDownListFor(m=> (m.diensten[i].DienstId), new SelectList(ViewBag.Diensten, "Value", "Text"))
}
You may try using
#foreach (var day in Model.diensten)
{
var currentDay=day;
#Html.DropDownListFor(currentDropDown=>currentDay, new SelectList(ViewBag.Diensten, "PropertyName_Holding_Value", "PropertyName_Holding_DisplayText"), new { })
} //This uses the Lambda Expression. Your dropdown Name/Id would be 1,2,3 etc. based on currentDay value.
OR
#foreach (var day in Model.diensten)
{
var currentDay=day;
var dropdownName=string.Format("diensten[{0}]",day-1); //If you want to model bind the selected dropdown value to input entity in POST request. The final dropdownName format should match the hierarchy of the property inside input entity/object. Even without this name formation, you can still POST the selected value back using Jquery/Javascript.
#Html.DropDownList(dropdownName, new SelectList(ViewBag.Diensten, "PropertyName_Holding_Value", "PropertyName_Holding_DisplayText"), new {})
} //
Note for Value Post back/model bind on full Page submit:
To be able to model bind/POST back values to the server, the html element names corresponding to the properties should be rendered as follows: Suppose if you display Employee.Department.Name, then name of textbox, displaying the Department Name in View should match Department_ReferenceName_Inside_Employee.Name for model binding.
Model:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public Department EmpDepartment { get; set; }
public List SubOrdinates { get; set; }
}
public class Department
{
public string Name { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
//Prepare the model and send it to the view
Employee emp = new Employee { EmpDepartment = new Department { Name = "IT" } };
emp.SubOrdinates = new List<Employee> { new Employee { Name = "Emp1" }, new Employee { Name = "Emp2" } };
return View(emp);
}
[HttpPost]
public ActionResult Index(Employee emp)
{ //Put a break-point here and see how the modified values in view are flowing into emp..
return View(emp);
}
public ActionResult About()
{
return View();
}
}
View:
#model MvcApplication.Models.Employee
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.EmpDepartment.Name)
#Html.LabelForModel("SubOrdinates :")
for (int i = 0; i < #Model.SubOrdinates.Count; i++)
{
#Html.TextBoxFor(m => (m.SubOrdinates[i].Name))
}
<input type="submit" name="name" value="Submit" /> }
ViewSource/PageSource:
The above text box syntax will be rendered as :
<input id="EmpDepartment_Name" name="EmpDepartment.Name" type="text" value="IT" /> <!--See above html : name=EmpDepartment.Name -->
<label for="">SubOrdinates :</label>
<input id="SubOrdinates_0__Name" name="SubOrdinates[0].Name" type="text" value="Emp1" />
<input id="SubOrdinates_1__Name" name="SubOrdinates[1].Name" type="text" value="Emp2" /> <!--See above html for how collection item Name(s) are being renderd by view engine-->
<input type="submit" name="name" value="Submit" />
#foreach (var day in Model.diensten)
{
var currentDay = day;
#Html.DropDownListFor(x => currentDay, new SelectList(ViewBag.Diensten, "Value", "Text"), new { #id = "DienstList" })
}
List<MvcApplication1.Models.Country> cntry = db.Countries.ToList();
SelectListItem sss = new SelectListItem();
List<SelectListItem> sltst = new List<SelectListItem>();
sss.Text = "Select";
sss.Value = "0";
sltst.Add(sss);
foreach (MvcApplication1.Models.Country s in cntry){
SelectListItem s1 = new SelectListItem();
s1.Text = s.Country1;
s1.Value = Convert.ToString(s.Id);
sltst.Add(s1);}
#Html.DropDownList("country", sltst, new { #id = "country" })
I hope I explain this correctly..
What I am trying to do is build up a session array with a list of products in.
Then display these on a form in text boxes with quantiles next to them and be able to submit them. I think I need to use template editor. But I don't know how to put data into the list of items.
This is how my session variable is currently being populated..
IList<EnqProduct> items2 = Session["enquiry"] as IList<EnqProduct>;
desc = desc.Replace(",", "");
EnqProduct item = new EnqProduct();
item.Id = (items2.Count + 1).ToString();
item.Product = desc;
item.Quantity = "0";
items2.Add(item);
So desc, can be productone, product two etc.
Enquiry Product model:
namespace MvcEditorTemplates.Models
{
public class EnqProduct
{
public string Id { get; set; }
public string Product { get; set; }
public string Quantity { get; set; }
}
}
Normal Enquiry Model:
public class Enquiry
{
public List<EnqProduct> EnqProduct { get; set; }
}
How i am trying to populate the model, but this is static. I need it to be populated from the array items:
var EnquiryModel = new Enquiry {
EnqProduct = items2.Select(c => new EnqProduct()
{
Quantity = c.Quantity,
Product = c.Product
})
};
Enquiry product template view:
#model MvcEditorTemplates.Models.EnqProduct
<div class="fl">
<p>
#Html.LabelFor(x => x.Product)
#Html.TextBoxFor(x => x.Product)
</p>
<p>
#Html.LabelFor(x => x.Quantity)
#Html.TextBoxFor(x => x.Quantity)
</p>
</div>
This is how im trying to get it to be displayed din the view:
#Html.EditorFor(model => model.EnqProduct)
EDIT:
at items2.Select(c => new EnqProduct()
i get a IEnumerbale error something about cast?
Try something like this:
public class ErrorMessage
{
public DateTime ErrorDate { get; set; }
public string ErrorText { get; set; }
public int DexRowId { get; set; }
}
public class Transaction
{
public string TransactionType { get; set; }
public string Processed { get; set; }
public DateTime UpdateDate { get; set; }
public int DexRowID { get; set; }
public string Text { get; set; }
}
public class Result
{
public List<ErrorMessage> errorMessageList { get; set; }
public List<Transaction> transactionList { get; set; }
}
In your controller:
List<Transaction> transactionList = ...;//query to populate your list;
List<ErrorMessage> errorMessageList = ...;//query to populate your list;
Result result = new Result();
result.ErrorMessageList = errorMessageList;
result.TransactionList = transactionList;
return View(result);
and in your view:
#model Models.Result
#{
ViewBag.Title = "Result";
Layout = "~/Views/Shared/_ResultLayout.cshtml";
}
EDIT:
#model IENumerable<MvcEditorTemplates.Models.EnqProduct>
#{
foreach( EnqProduct ep in #model)
{
.... your code comes here.........
}
}