In view I want display data from list ucz and insert data to listaOcen. display the list of ucz works but I have no idea to input data into list listaOcen
#using biblioteka;
#model dynamic
<tr>
#for (int i = 0; i < Model.dl;i++ )
{
td>#Model.Uczniowie[i]</td>
<td>
#Html.DropDownList(Model.listaOcen[i], new[] { //doesnt work
new SelectListItem() { Text = "5", Value = "5" },
new SelectListItem() { Text = "4+", Value = "4.75" },
}, "Select option")
<td>
</tr>
}
Controller:
public ActionResult Add(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var dataContext = db.Uczniowie;
var ucz = dataContext.Where(m => m.KlasaId == id)
.Select(m => m.Nazwisko + " " + m.Imie);
List<double> listOfOcena = new List<double>();
dynamic mymodel = new ExpandoObject();
mymodel.Uczniowie = ucz.ToList();
mymodel.dl = ucz.ToList().Count;
mymodel.listaOcen = listOfOcena;// enter the data from DropDownLists
return View(mymodel);
It is model.
public class Ocena
{
public string IdUcznia { get; set; }
public string Id { get; set; }
public string Przedmiot { get; set; }
public double Wartosc { get; set; }
public double waga { get; set; }
public DateTime? Data { get; set; }
public string Rodzaj { get; set; }
public string Opis { get; set; }
}
Please help :)
Robert, first of all try to avoid dynamic model. Create a viemodel for your action. e.g.
public class StudentMarkAssignViewModel
{
public long StudentId { get; set; }
public string FullName { get; set; }
public double Mark { get; set; }
}
then fill it in your action
[HttpGet]
public ActionResult Add(string id)
{
var model = new StudentMarkAssignViewModel[]
{
new StudentMarkAssignViewModel {StudentId = 1, FullName = "Martin", Mark = 0 },
new StudentMarkAssignViewModel {StudentId = 2, FullName = "Robert", Mark = 5 }
};
//here i use hardcoded valuse, but you should get them from your db
return View(model);
}
after that you can render list of your students and assign them marks and submit it to the server
#using WebApplication100.Models
#model StudentMarkAssignViewModel[]
#using (Html.BeginForm("Add", "StudentMarks", FormMethod.Post))
{
<table>
#for (var index = 0; index < Model.Length; index++)
{
<tr>
#Html.HiddenFor(x => Model[index].StudentId)
#Html.HiddenFor(x => Model[index].FullName)
<td>#Model[index].FullName</td>
<td>
#Html.DropDownListFor(x => Model[index].Mark, new SelectListItem[]{
new SelectListItem{ Value = "0", Text = "Not Rated", Selected = Model[index].Mark == 0 } ,
new SelectListItem{ Value = "5", Text = "5" , Selected = Model[index].Mark == 5 } ,
new SelectListItem{ Value = "4.75", Text = "4+" , Selected = Model[index].Mark == 4.75 }
})
</td>
</tr>
}
</table>
<button type="submit">submit</button>
}
after you submit the form, you'll get list of students and their marks on the server
[HttpPost]
public ActionResult Add(StudentMarkAssignViewModel[] marksModel)
{
/* do whatever you need with your model*/
return RedirectToAction("Index");
}
that's all. I hope you'll get the point.
Related
I have a quiz form,that it shows some question with it's answers(radio buttons),
the user must answer the questions and send it,
i made some class like this :
public class Question
{
public int Qid { get; set; }
public string Questionstext { get; set; }
public int selected { get; set; }
public List<Qitem> lst { get; set; }
}
public class Qitem
{
public int id { get; set; }
public string txt { get; set; }
}
then i send a list of Question into view :
List<Question> llst = new List<Question>
{
new Question
{
Qid = 1,
Questionstext = "is it true?",
lst = new List<Qitem>
{
new Qitem
{
txt = "yes",
id = 1
},
new Qitem
{
id = 2,
txt = "no"
}
}
},
new Question
{
Qid = 1,
Questionstext = "is it true 2?",
lst = new List<Qitem>
{
new Qitem
{
txt = "yes2",
id = 3
},
new Qitem
{
id = 4,
txt = "yes3"
}
}
}
};
return View(llst);
how can i show it and then submit the answers,
the answer must be put in 'selected' property of Question.
my problem is about view and Specially radio buttons.
Your view should be
#model List<Question>
#using (Html.BeginForm())
{
for (int i = 0; i < Model.Count; i++)
{
#Html.HiddenFor(m => m[i].Qid)
<h2>#Model[i].Questionstext</h2>
foreach (var answer in Model[i].lst)
{
<label>
#Html.RadioButtonFor(m => m[i].selected, answer.id, new { id = "" })
<span>#answer.txt </span>
</label>
}
}
<input type="submit" value="Save" />
}
which will post back to (assuming Index is the same name as the GET method used to generate this view).
public ActionResult Index(List<Question> model)
Side note: If you also want the Questionstext value to be posted as well, include #Html.HiddenFor(m => m[i].Questionstext)
my Model is
public class ChildMenu
{
public string Name { get; set; }
public string Comments { get; set; }
public List<UlrikenModel.ulriken_tblChildMenu> FormDetails { get; set; }
public long pkChildMenuID { get; set; }
public long fkSubMenuID { get; set; }
[Required(ErrorMessage = "Requird")]
public string ChildManuName { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
public string Events { get; set; }
public IList<SelectListItem> Drp_Submenu { get; set; }
}
My Controller action is :
public ActionResult FillDeptName()
{
UlrikenEntities db1 = new UlrikenModel.UlrikenEntities();
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "-Please select-", Value = "Selects
items" });
var cat = (from c in db1.ulriken_tblSubMenu where c.fkMainMenuID == 1 &&
c.Status == true select new { c.pkSubMenuID,c.SubManuName }).ToArray();
for (int i = 0; i < cat.Length; i++)
{
list.Add(new SelectListItem
{
Text = cat[i].SubManuName,
Value = cat[i].pkSubMenuID.ToString(),
Selected = (cat[i].pkSubMenuID == 1)
});
}
ViewBag.list = list;
return View("ChildMenuOfSubMenu", ViewBag.list);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult ChildMenuOfSubMenu(ChildMenu obj)
{
UlrikenEntities db = new UlrikenEntities();
ulriken_tblChildMenu objchild = new ulriken_tblChildMenu();
objchild.fkSubMenuID = obj.fkSubMenuID;
objchild.ChildMenuName = obj.ChildManuName;
objchild.cPageBody = obj.Name;
db.ulriken_tblChildMenu.Add(objchild);
db.SaveChanges();
return View("ChildMenuOfSubMenu");
}
and view is
#Html.DropDownListFor(m=>m.fkSubMenuID,
(IEnumerable<SelectListItem>)ViewBag.list,"Select" ,new { id = "ddlSubMenu" })
At start dropdown bind successfully but after saving data to database show an exception in
as "There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key
'fkSubMenuID'"
AnyBody guide me where am i doing wrong.
Move that code to the helper class:
public class ControllerHelper
{
public List<SelectListItem> FetchListItems()
{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "-Please select-", Value = "Selects items" });
var cat = (from c in db1.ulriken_tblSubMenu where c.fkMainMenuID == 1 &&
c.Status == true select new { c.pkSubMenuID,c.SubManuName }).ToArray();
for (int i = 0; i < cat.Length; i++)
{
list.Add(new SelectListItem
{
Text = cat[i].SubManuName,
Value = cat[i].pkSubMenuID.ToString(),
Selected = (cat[i].pkSubMenuID == 1)
});
}
return list;
}
}
And then your controller should looks like:
public ActionResult FillDeptName()
{
UlrikenEntities db1 = new UlrikenModel.UlrikenEntities();
ViewBag.list = new ControllerHelper().FetchListItems();
return View("ChildMenuOfSubMenu", ViewBag.list);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult ChildMenuOfSubMenu(ChildMenu obj)
{
UlrikenEntities db = new UlrikenEntities();
ulriken_tblChildMenu objchild = new ulriken_tblChildMenu();
objchild.fkSubMenuID = obj.fkSubMenuID;
objchild.ChildMenuName = obj.ChildManuName;
objchild.cPageBody = obj.Name;
db.ulriken_tblChildMenu.Add(objchild);
db.SaveChanges();
ViewBag.list = new ControllerHelper().FetchListItems();
return View("ChildMenuOfSubMenu");
}
Of course:
new ControllerHelper().FetchListItems();
should be a field in the controller class, for example:
private ControllerHelper controlerHelper;
You can use Interface instead of concerete implementation, if you use DI.
Regards
This is my model class:
public class EstimateModel:estimate
{
public string EstimateNo { get; set; }
//public SelectList Customer { get; set; }
//[DisplayName("Customer ID :")]
public int CustID { get; set; }
[DisplayName("Customer Name :")]
public string CustFname { get; set; }
[DisplayName("Company Name :")]
public string CompanyName { get; set; }
[DisplayName("Total:")]
public decimal total { get; set; }
[DisplayName("Tax1 :")]
public decimal tax1 { get; set; }
public decimal tax2 { get; set; }
public decimal tax3 { get; set; }
public decimal subtot { get; set; }
[DisplayName("Discount :")]
public decimal Discount { get; set; }
[DisplayName("GrandTotal:")]
public decimal grandtotal { get; set; }
public List<estimate> estimates { get; set; }
public EstimateModel()
{
estimates = new List<estimate>();
}
}
This is my controller code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(EstimateModel employee)
{
//employee.Customer= new SelectList("CustID","CustFName");
DataTable dt = new DataTable();
//for (int i = 0; i < employee.estimates.Count; i++)
//{
// total = total + employee.estimates[i].Amount;
//} ViewBag.Message = total;
//Skill abc = new Skill();
var sys = db.EstimateMasters.Create();
// var user = db.Adils.Create();
sys.EstimateNo = employee.EstimateNo;
for(int i=0 ;i<employee.estimates.Count;i++)
{
sys.EstimateNo = employee.EstimateNo;
sys.CustID = employee.CustID;
sys.ProductName = employee.estimates[i].ProductName;
sys.Quantity = employee.estimates[i].Quantity;
sys.Price = employee.estimates[i].Price;
sys.Amount = employee.estimates[i].Amount;
sys.Total=employee.total;
sys.Tax1=employee.tax1;
sys.Tax2 = employee.tax2;
sys.Tax3 = employee.tax3;
sys.Discount = employee.Discount;
sys.SubTotal = employee.subtot;
sys.GrandTotal = employee.grandtotal;
db.EstimateMasters.Add(sys);
db.SaveChanges();
}
This is my view code:
<div> #Html.LabelFor(m =>m.CustID)
#Html.DropDownList("CustID", "---Select---")
</div>
</div>
<div>
#Html.LabelFor(m => m.CustFname)
#Html.TextBoxFor(m =>m.CustFname)
#Html.LabelFor(m=>m.CompanyName)
#Html.TextBoxFor(m =>m.CompanyName)
</div>
I am getting this error on DropDownList: The ViewData item that has the key 'CustID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'. Can anyone help me?
You have to pass list to dropdown but here you are passing CustID and that is Integer. This is causing error.
Try following code:
1) Create a list with your items.
#{
List<SelectListItem> CustIDlistItems= new List<SelectListItem>();
CustIDlistItems.Add(new SelectListItem
{
Text = "text1",
Value = "value1"
});
CustIDlistItems.Add(new SelectListItem
{
Text = "text2",
Value = "value2",
Selected = true
});
CustIDlistItems.Add(new SelectListItem
{
Text = "text3",
Value = "value3"
});
}
2) Pass newly created list to view with list as a parameter.
#Html.DropDownListFor(model => model.Yourproperty, CustIDlistItems, "-- Select Status --")
Hope this will help you..!
EDIT :
You can utilize following example for creating dynamic list from database.
public IEnumerable<SelectListItem> GetTrainingSubjectsList(int selectedValue)
{
List<SelectListItem> TrainingSubjectsList = new List<SelectListItem>();
TrainingSubjectsList.Add(new SelectListItem() { Selected = true, Text = "Select Subject", Value = "" });
var TrainingSubjects = (from subjects in _context.TrainingDetails.Where(c => c.IsDeleted == false)
select subjects).ToList();
foreach (TrainingDetail TrainingDetail in TrainingSubjects)
{
SelectListItem Item = new SelectListItem();
Item.Text = TrainingDetail.Title;
Item.Value = TrainingDetail.TrainingDetailId.ToString();
if (selectedValue == TrainingDetail.TrainingDetailId)
{
Item.Selected = true;
}
TrainingSubjectsList.Add(Item);
}
return TrainingSubjectsList;
}
HI I am stuck in getting data that i need to display in kendo UI GRID , Initially I am able to see the button and textbox and grid as well but when i enter the value in textbox and then press the button i need to show that entered values in kendo UI GRID ...
When I run this application in google chrome it was giving empty grid,after enters the value and then press the submit button but when I run this one in IE8 it was giving error like this at starting stage itself....
Unhandled exception at line 238, column 37 in Function code
0x800a138f - Microsoft JScript runtime error: 'data.EmployeeDetails.EmployeeId' is null or not an object
and this is my model
public class TextBoxGrid
{
public string EnteredValue { get; set; }
public List<EmployeeDetails> employees;
}
public class ParentViewModel
{
public EmployeeDetails EmployeeDetails { get; set; }
public TextBoxGrid TextBoxGrid { get; set; }
}
public class EmployeeDetails
{
public string EmployeeId { get; set; }
public string ManagerId { get; set; }
}
this is my controller
public class EnterValuesGridController : Controller
{
private static List<EmployeeDetails> empdtls;
public ActionResult Index( ParentViewModel model)
{
var viewmodel = new ParentViewModel
{
TextBoxGrid = new TextBoxGrid { employees = GetEmployee().ToList() }
};
return View(viewmodel);
}
[HttpPost]
public ActionResult PostValues(TextBoxGrid model)
{
TempData["enteringValue"] = model.EnteredValue;
var viewmodel = new ParentViewModel
{
TextBoxGrid = new TextBoxGrid { employees = GetEmployee().ToList() }
};
//ParentViewModel p = new ParentViewModel();
//TextBoxGrid t = new TextBoxGrid();
//t.EnteredValue = "a";
//TempData["a1"] = t.EnteredValue;
//t.employees = GetEmployee().ToList();
//p.TextBoxGrid = t;
//return View("Index", p);
return View("Index", viewmodel);
}
public IEnumerable<EmployeeDetails> GetEmployee()
{
string enteredValueId =(string) TempData["enteringValue"];
string managerId = "M" +enteredValueId;
empdtls = new List<EmployeeDetails>();
EmployeeDetails em1 = new EmployeeDetails();
em1.EmployeeId = enteredValueId;
em1.ManagerId = managerId;
empdtls.Add(em1);
return empdtls.AsEnumerable();
}
public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request)
{
return Json(GetOrders().ToDataSourceResult(request));
}
private IEnumerable<EmployeeDetails> GetOrders()
{
return GetEmployee().AsEnumerable();
}
}
and this is my view
#model KendoPratapSampleMVCApp.Models.ParentViewModel
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm("PostValues", "EnterValuesGrid", FormMethod.Post))
{
#Html.TextBoxFor(m=>m.TextBoxGrid.EnteredValue)
<input type="submit" name="Submitbutton1" value="Submit1" />
#(Html.Kendo().Grid<KendoPratapSampleMVCApp.Models.ParentViewModel>()
.Name("grid")
.Columns(columns => {
columns.Bound(s=>s.EmployeeDetails.EmployeeId).Filterable(false).Width(100);
columns.Bound(s => s.EmployeeDetails.ManagerId).Filterable(false).Width(100);
})
.Filterable()
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("Orders_Read", "EnterValuesGrid"))
)
)
}
I am not sure where I am doing wrong, Would you pls suggest any ideas on this one ..
Many thanks...., Do i need to do any changes in UI GRID I have tried changing the post values method ...but it didnot worked for me ...
UPDATE :
changed tempData to view Bag...
[HttpPost]
public ActionResult PostValues(ParentViewModel model)
{
ViewBag.item = model.TextBoxGrid.EnteredValue;
var viewmodel = new ParentViewModel
{
TextBoxGrid = new TextBoxGrid { employees = GetEmployee().ToList() }
};
//ParentViewModel p = new ParentViewModel();
//TextBoxGrid t = new TextBoxGrid();
//t.EnteredValue = "a";
//TempData["a1"] = t.EnteredValue;
//t.employees = GetEmployee().ToList();
//p.TextBoxGrid = t;
//return View("Index", p);
return View("Index", viewmodel);
}
public IEnumerable<EmployeeDetails> GetEmployee()
{
string enteredValueId = (string)ViewBag.item;
string managerId = "M" +enteredValueId;
empdtls = new List<EmployeeDetails>();
EmployeeDetails em1 = new EmployeeDetails();
em1.EmployeeId = enteredValueId;
em1.ManagerId = managerId;
empdtls.Add(em1);
return empdtls;
}
Hi pratap i just update your code,
Model
public class TextBoxGrid
{
public string EnteredValue { get; set; }
public List<EmployeeDetails> employees;
}
public class ParentViewModel
{
public EmployeeDetails EmployeeDetails { get; set; }
public TextBoxGrid TextBoxGrid { get; set; }
}
public class EmployeeDetails
{
public string EnteredValue { get; set; }
public string EmployeeId { get; set; }
public string ManagerId { get; set; }
}
View
#model TwoModelInSinglePageModel.EmployeeDetails
#{
ViewBag.Title = "Index";
}
<script src="~/Script/Jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="~/Script/jquery-ui-1.8.20.min.js" type="text/javascript"></script>
<script src="#Url.Content("~/Script/kendo.all.min.js")" type="text/javascript"></script>
<script src="~/Script/kendo.web.min.js" type="text/javascript"></script>
<script src="~/Script/kendo.aspnetmvc.min.js" type="text/javascript"></script>
#using (Html.BeginForm("PostValues", "Test", FormMethod.Post))
{
#Html.TextBoxFor(m => m.EnteredValue)
<input type="submit" name="Submitbutton1" value="Submit1" />
#(Html.Kendo().Grid<TwoModelInSinglePageModel.EmployeeDetails>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(s => s.EmployeeId);
columns.Bound(s => s.ManagerId);
})
.Filterable()
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("Orders_Read", "Test"))
)
)
}
Controller
private static List<EmployeeDetails> empdtls;
public ActionResult PostValues()
{
return View();
}
[HttpPost]
public ActionResult PostValues(EmployeeDetails model)
{
ViewBag.item = model.EnteredValue;
ParentViewModel viewmodels = new ParentViewModel
{
TextBoxGrid = new TextBoxGrid { employees = GetEmployee().ToList() }
};
ParentViewModel viewmodel = new ParentViewModel();
EmployeeDetails em1 = new EmployeeDetails();
for (int i = 0; i < viewmodels.TextBoxGrid.employees.Count(); i++)
{
em1.EmployeeId = viewmodels.TextBoxGrid.employees[i].EmployeeId;
em1.ManagerId = viewmodels.TextBoxGrid.employees[i].ManagerId;
viewmodel.EmployeeDetails = em1;
}
Session["EM1"] = em1;
return View("PostValues", em1);
}
public List<EmployeeDetails> GetEmployee()
{
string enteredValueId = (string)ViewBag.item;
string managerId = "M" + enteredValueId;
empdtls = new List<EmployeeDetails>();
EmployeeDetails em1 = new EmployeeDetails();
em1.EmployeeId = enteredValueId;
em1.ManagerId = managerId;
if (Session["EM1"] != null)
{
em1 = Session["EM1"] as EmployeeDetails;
empdtls.Add(em1);
Session["EM1"] = null;
}
else
{
empdtls.Add(em1);
}
return empdtls;
}
public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request, EmployeeDetails model)
{
return Json(GetEmployee().ToDataSourceResult(request));
}
OK, I read through your post again and you want to submit the form when click on the button actually. So, let's try to put the value in the session
Session["enteringValue"] = model.EnteredValue;
And you can retrieve it using
string enteredValueId = (string)(Session["enteringValue"]);
I have the following code:
public class OrganisationController : Controller
{
//
// GET: /Organisation/
public ActionResult Update()
{
var fisherman = new RoleType {Id = 1, Name = "Fisherman"};
var manager = new RoleType {Id = 2, Name = "Manager"};
var deckhand = new RoleType {Id = 3, Name = "Deckhand"};
var roleTypes = new List<RoleType>
{
fisherman, manager, deckhand
};
ViewBag.Roles = new SelectList(roleTypes, "Id", "Name");
return View(
new Organisation
{
Name = "Fish Co.",
People = new List<Person>
{
new Person
{
Name = "Squid",
RoleType = fisherman
},
new Person
{
Name = "Michael",
RoleType = manager
},
new Person
{
Name = "John",
RoleType = deckhand
}
}
});
}
[HttpPost]
public ActionResult Update(Organisation org)
{
return View();
}
}
public class Organisation
{
public string Name { get; set; }
public IList<Person> People { get; set; }
}
public class Person
{
public string Name { get; set; }
public RoleType RoleType { get; set; }
}
public class RoleType
{
public int Id { get; set; }
public string Name { get; set; }
}
In Update.cshtml
#model Models.Organisation
<form action="" method="post" enctype="multipart/form-data">
#Html.EditorFor(x => x.Name)
#Html.EditorFor(x => x.People)
<input type="submit"/>
</form>
In the EditorTemplates Person.cshtml:
#model Models.Person
#Html.EditorFor(x => x.Name)
#if(Model != null)
{
#Html.DropDownListFor( x => x.RoleType.Id, (SelectList)ViewBag.Roles)
}
I was expecting to be able to get to a page where I can update the organisation name, the people names and their roles. The trouble is that I can't get the selected item to be set for the dropdowns. I thought x => x.RoleType.Id would do this for me.
Does anyone know how I can get this to work?
Try this constructor: SelectList Constructor (IEnumerable, String, String, Object)
public SelectList(
IEnumerable items,
string dataValueField,
string dataTextField,
Object selectedValue
)
Something like this:
#Html.DropDownListFor( x => x.RoleType.Id, new SelectList((List<RoleType>)ViewBag.Roles, "Id", "Name", Model.RoleType.Id))