Null value in viewmodel after Post Action - asp.net-mvc

I am getting null values in the controller http post part from the view model. All the values are null. I am not able to access the view model properties and select list values as well. How to solve the null values and access the selected city from the model for updating the database using db context.
I searched other similar questions but those results didnt help.
It will be of great help if anyone can solve the issue.
Model Class:
namespace MvcCoreAngular.ViewModels
{
public class DetailedResultEdit
{
public int employeeid { get; set; }
public string name { get; set; }
public List<SelectListItem> citieslist { get; set; }
public int cityid { get; set; }
public string department { get; set; }
public string gender { get; set; }
}
}
HTML:
#model IEnumerable<MvcCoreAngular.ViewModels.DetailedResultEdit>
#{
ViewData["Title"] = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm("Edit", "Home", FormMethod.Post))
{
#foreach (var item in Model)
{
<table>
<tr>
#Html.Label("Name")
#Html.TextBoxFor(model => item.name)
<br />
</tr>
<tr>
#Html.Label("Department")
#Html.TextBoxFor(model => item.department)
<br />
</tr>
<tr>
#Html.Label("Cities")
#Html.DropDownListFor(model => item.cityid, item.citieslist, "", null)
<br />
</tr>
<tr>
<input type="submit" value="Submit" id="btnSubmit" />
</tr>
</table>
}
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(DetailedResultEdit mo)
{
//IEnumerable<tblcities> citieslist = from c in _context.tblcities.ToList<tblcities>().GroupBy(x=> x.cityname).Select(x=> x.First());
if (ModelState.IsValid) {
var empdata = _context.tblemployee.Find(mo.employeeid);
empdata.cityid = mo.cityid;
empdata.department = mo.department;
empdata.name = mo.name;
_context.SaveChanges();
}

Firstly,your code don't bind the data correctly,so the edit action cannot get the data.Besides,you didn't pass employeeid to action,so you can add a hidden input in the view,and then you can use _context.tblemployee.Find.
Here is a demo worked:
Controller:
[HttpGet]
public IActionResult Edit() {
List<tblemployee> tblemployees = _context.tblemployee.ToList();
List<DetailedResultEdit> detailedResultEdits = new List<DetailedResultEdit>();
List<SelectListItem> list = new List<SelectListItem> { new SelectListItem { Text = "NY", Value = "1" }, new SelectListItem { Text = "Boston", Value = "2" }, new SelectListItem { Text = "Dover", Value = "3" } };
foreach (tblemployee t in tblemployees) {
DetailedResultEdit temp = new DetailedResultEdit();
temp.cityid = t.cityid;
temp.name = t.name;
temp.employeeid = t.employeeid;
temp.department = t.department;
temp.gender = t.gender;
temp.citieslist = list;
detailedResultEdits.Add(temp);
}
return View(detailedResultEdits);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(DetailedResultEdit mo)
{
if (ModelState.IsValid)
{
var empdata = _context.tblemployee.Find(mo.employeeid);
empdata.cityid = mo.cityid;
empdata.department = mo.department;
empdata.name = mo.name;
_context.Attach(empdata).State = EntityState.Modified;
_context.SaveChanges();
Edit();
}
return View();
}
View:
#model IEnumerable<DetailedResultEdit>
#{
ViewData["Title"] = "Edit";
}
<h2>Edit</h2>
#foreach (var item in Model)
{
#using (Html.BeginForm("Edit", "TestDB", FormMethod.Post))
{
<table>
<tr>
<input hidden name="employeeid" value="#item.employeeid" class="form-control" />
#Html.Label("Name")
<input name="name" value="#item.name" class="form-control" />
<br />
</tr>
<tr>
#Html.Label("Department")
<input name="department" value="#item.department" class="form-control" />
<br />
</tr>
<tr>
#Html.Label("Cities")
<select name="cityid"
asp-for="#item.cityid"
asp-items="#item.citieslist">
</select>
<br />
</tr>
<tr>
<input type="submit" value="Submit" id="btnSubmit" />
</tr>
</table>
}
}
tblemployee:
public class tblemployee
{
[Key]
public int employeeid { get; set; }
public string name { get; set; }
public int cityid { get; set; }
public string department { get; set; }
public string gender { get; set; }
}
result:

Related

Get The Name Field Class Razor?

public class ViewModel_Index
{
public int Id { get; set; }
public string Name { get; set; }
[UIHint("_Date")]
public DateTime bd { get; set; }
[UIHint("_EnumRadioButton")]
public Gender sex{ get; set; }
}
File _EnumRadioButton.cshtml
#model Enum
#{
List<SelectListItem> LstT = new List<SelectListItem>();
Array ev = Enum.GetValues(Model.GetType());
foreach (Enum item in ev)
{
LstT.Add(new SelectListItem
{
Text = Sample.Service.CustomExtension.EnumExtension.ToDescription(item),
Value = item.ToString()
});
}
#Helpers.RadioButtonList(Model.GetType().Name , LstT)
}
File Helpers.cshtml
#helper RadioButtonList(string groupName, IEnumerable<System.Web.Mvc.SelectListItem> items)
{
<div class="RadioButtonList">
#foreach (var item in items)
{
#item.Text
<input type="radio" name="#groupName" value="#item.Value"
#if (item.Selected) { <text> checked="checked" </text> } />
}
</div>
}
index
#using (#Html.BeginForm("test", "Home", FormMethod.Post))
{
#Html.EditorForModel()
<button type="submit">send</button>
}
controller
[HttpPost]
public ActionResult test(ViewModel_Index a)
{
return View();
}
view source
<div class="RadioButtonList">
زن<input type="radio" name="Gender" value="Woman"/>
مرد<input type="radio" name="Gender" value="Man"/>
هیچکدام<input type="radio" name="Gender" value="Non"/>
</div>
File _EnumRadioButton.cshtml
prablem:
name radio must be same name field
radio Name="gender"
field Name="sex"
#Helpers.RadioButtonList(Model.GetType().Name , LstT)

MVC Controllers get value of 'Checkboxlist'

I'm probably a idiot here but I'm having problems getting the value of whether or not a checkbox is checked/selected or not. Here's what I've got so far:
In my Model:
public IEnumerable<SelectListItem> Insurers
{
get
{
var list = new List<SelectListItem>();
string zInsurersList = "Age UK,Be Wiser,Call Connection,Churchill,Sainsbury's,Direct Line,Hastings Direct,LV=,Nationwide,RIAS,Swinton";
string[] zInsurers = zInsurersList.Split(',');
foreach (string aInsurer in zInsurers)
{
list.Add(new SelectListItem() { Text = aInsurer, Value = aInsurer, Selected=false});
}
return list;
}
}
}
And my view:
#foreach (var insurer in #Model.Insurers)
{
var zInsurer = insurer.Text;
var zValue = insurer.Value;
<tr>
<td style="width: 120px; height: 35px;"><span id="#zInsurer">#zInsurer</span></td>
<td style="width: 40px; height: 35px;"><input id="#zInsurer" type="checkbox" name="#zInsurer"></td>
</tr>
}
So in my controller I'm trying to loop the list and get the value of whether or not the user has selected the option:
foreach (var item in model.Insurers)
{
//if (item.GetType() == typeof(CheckBox))
//string controlVal = ((SelectListItem)item).Selected.ToString();
zInsurers = zInsurers + item.Text + " " + ((SelectListItem)item).Selected.ToString() + "<br/>";
}
But the value always returns false.
Could someone spare a few mins to highlight my stupidity please?
Thanks,
Craig
There are a lot of ways to do it. I normally add String Array in model to collect selected values.
public string[] SelectedInsurers { get; set; }
<input type="checkbox" name="SelectedInsurers" value="#insurer.Value" />
Here is the sample code -
MyModel
public class MyModel
{
public string[] SelectedInsurers { get; set; }
public IEnumerable<SelectListItem> Insurers
{
get
{
var list = new List<SelectListItem>();
string zInsurersList = "Age UK,Be Wiser,Call Connection,Churchill,Sainsbury's,Direct Line,Hastings Direct,LV=,Nationwide,RIAS,Swinton";
string[] zInsurers = zInsurersList.Split(',');
foreach (string aInsurer in zInsurers)
{
list.Add(new SelectListItem { Text = aInsurer, Value = aInsurer, Selected = false });
}
return list;
}
}
}
Action Methods
public ActionResult Index()
{
return View(new MyModel());
}
[HttpPost]
public ActionResult Index(MyModel model)
{
return View();
}
View
#using (Html.BeginForm())
{
foreach (var insurer in #Model.Insurers)
{
<input type="checkbox" name="SelectedInsurers" value="#insurer.Value" /> #insurer.Text<br/>
}
<input type="submit" value="Post Back" />
}
Result
Firstly, your property Insurers should not be IEnumerable<SelectListItem> (tha'ts for binding a collection to a dropdownlist), and in any case, that kind of logic does not belong in a getter (and whats the point of creating a comma delimited string and then splitting it? - just create an array of strings in the first place!). Its not really clear exactly what you trying to do, but you should be creating a view model and doing it the MVC way and making use of its model binding features
View model
public class InsurerVM
{
public string Name { get; set; }
public bool IsSelected { get; set; }
}
Controller
public ActionResult Edit()
{
// This should be loaded from some data source
string[] insurers = new string[] { "Age UK", "Be Wiser", "Call Connection" };
List<InsurerVM> model = insurers.Select(i => new InsurerVM() { Name = i }).ToList();
return View(model);
}
View
#model List<InsurerVM>
#using(Html.BeginForm())
{
for (int i = 0; i < Model.Count; i++)
{
#Html.HiddenFor(m => m[i].Name)
#Html.CheckBoxFor(m => m[i].IsSelected)
#Html.LabelFor(m => m.[i].IsSelected, Model[i].Name)
}
<input type="submit" value="Save" />
}
Post method
[HttpPost]
public ActionResult Edit(IEnumerable<InsurerVM> model)
{
// loop each item to get the insurer name and the value indicating if it has been selected
foreach(InsurerVM insurer in model)
{
....
}
}
In reality, Insurers would be an object with an ID and other properties so it can be identified and have a relationship with other entities.
As to why you code is not working. Your property does not have a setter so nothing that posted back could be bound anyway. All the method is doing is initializing your model then calling the getter which creates a new IEnumerable<SelectListItem> (identical to the one you sent to the view in the first place). Not that it would have mattered anyway, your checkboxes have name attributes name="Age_UK", name=Be_Wiser" etc which have absolutely no relationship to your model so cant be bound
That is because the modelbinding can't process your values.
You should look into model binding.
Try something like this:
#for (var countInsurer = 0; Model.Insurers.Count > countInsurer++)
{
var zInsurer = insurer.Text;
var zValue = insurer.Value;
<tr>
<td style="width: 120px; height: 35px;"><span id="#zInsurer">#zInsurer</span></td>
<td style="width: 40px; height: 35px;">#Html.CheckBoxFor(m=> Model.Insurers[countInsurer], new {name = zInsurer})</td>
</tr>
}
#for(int i = 0; i < Model.List.Count; i++)
{
#Html.CheckBoxFor(m => Model.List[i].IsChecked, htmlAttributes: new { #class = "control-label col-md-2" })
#Model.List[i].Name
#Html.HiddenFor(m => Model.List[i].ID)
#Html.HiddenFor(m => Model.List[i].Name)
<br />
}
in controller
StringBuilder sb = new StringBuilder();
foreach (var item in objDetail.List)
{
if (item.IsChecked)
{
sb.Append(item.Value + ",");
}
}
ViewBag.Loc = "Your preferred work locations are " + sb.ToString();
I Get Module And Right from Module and Rights Table How to Send All Data To RoleRight Table All Checkbox value
public class RoleRightModel
{
public ModuleModel _ModuleModel { get; set; }
public RightsModel _RightsModel { get; set; }
public RolesModel _RolesModel { get; set; }
public List<ModuleModel> _ModuleModelList { get; set; }
public List<RightsModel> _RightsModelList { get; set; }
public List<RolesModel> _RolesModelList { get; set; }
public List<RoleRightModel> _RoleRightModelList { get; set; }
public int RoleRightID { get; set; }
public int RoleID { get; set; }
public int ModuleID { get; set; }
public int FormMode { get; set; }
public int RightCode { get; set; }
public bool? RowInternal { get; set; }
public byte? IsAuthorised { get; set; }
public int? CreationID { get; set; }
public DateTime? CreationDate { get; set; }
public int? LastModificationID { get; set; }
public DateTime? LastModificationDate { get; set; }
public byte? RowStatus { get; set; }
public string RoleName { get; set; }
}
Razor
#foreach(var item in Model._ModuleModelList.Where(x => x.Level == 1))
{
<ul style="display: block;">
<li><i class="fa fa-plus"></i>
<label>
#if (item.Level == 1)
{
<input id="node-0-1" data-id="custom-1" type="checkbox" name="Module" value="#item.ModuleID"#(Model._ModuleModel.ModuleID)? "checked":"">
#item.ModuleName
}
</label>
#foreach (var lavel1 in Model._ModuleModelList.Where(x => x.ParentModuleID == item.ModuleID))
{
<ul>
<li><i class="fa fa-plus"></i>
<label>
<input id="node-0-1-1" data-id="custom-1-1" type="checkbox" name="Module" value="#lavel1.ModuleID"#(Model._ModuleModel.ModuleID)? "checked":"">
#lavel1.ModuleName
</label>
#foreach (var lavel2 in Model._ModuleModelList.Where(x => x.ParentModuleID == lavel1.ModuleID))
{
<ul>
<li><i class="fa fa-plus"></i>
<label>
<input id="node-0-1-1-1" data-id="custom-1-1-1" type="checkbox" name="Module" value="#lavel2.ModuleID"#(Model._ModuleModel.ModuleID)? "checked":"">
#lavel2.ModuleName
</label>
#foreach (var lavel3 in Model._RightsModelList.Where(x => x.ModuleId == lavel2.ModuleID))
{
<ul>
<li>
<label>
<input id="node-0-1-1-1-1" data-id="custom-1-1-1-1" type="checkbox" name="Right" value="#lavel3.RightID"#(Model._RightsModel.RightID)? "checked":"">
#lavel3.RightName
</label>
</li>
</ul>
}
</li>
</ul>
}
</li>
</ul>
}
</li>
</ul>
}

MVC post a list of complex objects

I have a FeedbackViewModel that contains a list of questions:
public class FeedbackViewModel
{
public List<QuestionViewModel> Questions { get; set; }
}
This QuestionViewModel is an object that can be inherited by 5 different types of questions
public class QuestionViewModel
{
public string QuestionText { get; set; }
public string QuestionType { get; set; }
}
An example of one of the inheriting question types:
public class SingleQuestionViewModel : QuestionViewModel
{
public string AnswerText { get; set; }
}
In the HttpGet of the Index action in the controller I get the questions from the database and add the correct question type in list of question in the FeedbackViewModel Then I render this model in the view:
#using (Html.BeginForm())
{
//foreach (var item in Model.Questions)
for (int i = 0; i < Model.Questions.Count; i++)
{
<div class="form-group">
#Html.DisplayFor(modelItem => Model.Questions[i].QuestionText, new { #class = "control-label col-md-4" })
<div class="col-md-6">
#if (Model.Questions[i].QuestionType == "Single")
{
#Html.EditorFor(modelItem => (Model.Questions[i] as OpenDataPortal.ViewModels.SingleQuestionViewModel).AnswerText)
}
else if (Model.Questions[i].QuestionType == "Multiple")
{
#Html.TextAreaFor(modelItem => (Model.Questions[i] as OpenDataPortal.ViewModels.SingleQuestionViewModel).AnswerText)
}
else if (Model.Questions[i].QuestionType == "SingleSelection")
{
#Html.RadioButtonForSelectList(modelItem => (Model.Questions[i] as OpenDataPortal.ViewModels.SingleSelectionQuestionViewModel).SelectedAnswer,
(Model.Questions[i] as OpenDataPortal.ViewModels.SingleSelectionQuestionViewModel).SelectionAnswers)
}
else if (Model.Questions[i].QuestionType == "MultipleSelection")
{
#Html.CustomCheckBoxList((Model.Questions[i] as OpenDataPortal.ViewModels.MultipleSelectionQuestionViewModel).AvailableAnswers)
}
else if (Model.Questions[i].QuestionType == "UrlReferrer")
{
#Html.EditorFor(modelItem => (Model.Questions[i] as OpenDataPortal.ViewModels.SingleQuestionViewModel).AnswerText)
}
</div>
</div>
<br />
}
<br />
<button type="submit">Submit</button>
}
Now, I simply can't get it to post the list of questions in the model. Is it even possible to post a list of different object types?
Edit: Following is the list of data within the post that I discovered using Fiddler:
After much research I've found two solutions:
One is to write HTML that has hardcoded Id's and Names
Two is to convert your ICollection/IEnumerable to an Array or List (i.e IList something with an 'index'), and have an Array object in your BindingModel in your Controller POST Action.
Thanks to Phil Haack's (#haacked) 2008 blog post http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/
Which is still relevant to how the default ModelBinder works today for MVC.
(NB: the links in Phil's article to sample porject and extension methods are broken)
HTML snippet that inspired me:
<form method="post" action="/Home/Create">
<input type="hidden" name="products.Index" value="cold" />
<input type="text" name="products[cold].Name" value="Beer" />
<input type="text" name="products[cold].Price" value="7.32" />
<input type="hidden" name="products.Index" value="123" />
<input type="text" name="products[123].Name" value="Chips" />
<input type="text" name="products[123].Price" value="2.23" />
<input type="submit" />
</form>
Post array looks a bit like:
products.Index=cold&products[cold].Name=Beer&products[cold].Price=7.32&products.Index=123&products[123].Name=Chips&products[123].Price=2.23
Model:
public class CreditorViewModel
{
public CreditorViewModel()
{
this.Claims = new HashSet<CreditorClaimViewModel>();
}
[Key]
public int CreditorId { get; set; }
public string Comments { get; set; }
public ICollection<CreditorClaimViewModel> Claims { get; set; }
public CreditorClaimViewModel[] ClaimsArray {
get { return Claims.ToArray(); }
}
}
public class CreditorClaimViewModel
{
[Key]
public int CreditorClaimId { get; set; }
public string CreditorClaimType { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:N2}")]
public Decimal ClaimedTotalAmount { get; set; }
}
Controller GET:
public async Task<ActionResult> Edit(int id)
{
var testmodel = new CreditorViewModel
{
CreditorId = 1,
Comments = "test",
Claims = new HashSet<CreditorClaimViewModel>{
new CreditorClaimViewModel{ CreditorClaimId=1, CreditorClaimType="1", ClaimedTotalAmount=0.00M},
new CreditorClaimViewModel{ CreditorClaimId=2, CreditorClaimType="2", ClaimedTotalAmount=0.00M},
}
};
return View(model);
}
Edit.cshtml:
#Html.DisplayNameFor(m => m.Comments)
#Html.EditorFor(m => m.Comments)
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(m => Model.Claims.FirstOrDefault().CreditorClaimType)
</th>
<th>
#Html.DisplayNameFor(m => Model.Claims.FirstOrDefault().ClaimedTotalAmount)
</th>
</tr>
<!--Option One-->
#foreach (var item in Model.Claims)
{
var fieldPrefix = string.Format("{0}[{1}].", "Claims", item.CreditorClaimId);
<tr>
<td>
#Html.DisplayFor(m => item.CreditorClaimType)
</td>
<td>
#Html.TextBox(fieldPrefix + "ClaimedTotalAmount", item.ClaimedTotalAmount.ToString("F"),
new
{
#class = "text-box single-line",
data_val = "true",
data_val_number = "The field ClaimedTotalAmount must be a number.",
data_val_required = "The ClaimedTotalAmount field is required."
})
#Html.Hidden(name: "Claims.index", value: item.CreditorClaimId, htmlAttributes: null)
#Html.Hidden(name: fieldPrefix + "CreditorClaimId", value: item.CreditorClaimId, htmlAttributes: null)
</td>
</tr>
}
</table>
<!--Option Two-->
#for (var itemCnt = 0; itemCnt < Model.ClaimsArray.Count(); itemCnt++)
{
<tr>
<td></td>
<td>
#Html.TextBoxFor(m => Model.ClaimsArray[itemCnt].ClaimedTotalAmount)
#Html.HiddenFor(m => Model.ClaimsArray[itemCnt].CreditorClaimId)
</td></tr>
}
Form is processed in the Controller:
Post Model:
public class CreditorPostViewModel
{
public int CreditorId { get; set; }
public string Comments { get; set; }
public ICollection<CreditorClaimPostViewModel> Claims { get; set; }
public CreditorClaimPostViewModel[] ClaimsArray { get; set; }
}
public class CreditorClaimPostViewModel
{
public int CreditorClaimId { get; set; }
public Decimal ClaimedTotalAmount { get; set; }
}
Controller:
[HttpPost]
public ActionResult Edit(int id, CreditorPostViewModel creditorVm)
{
//...
Make sure you are rendering your view in order so that Model.Questions[i] renders in order.
For example, Model.Questions[0], Model.Questions[1], Model.Questions[2].
I noticed that if the order is not correct mvc model binder will only bind the first element.
Thanks for pointing me in the right direction with this post. I was struggling to get the syntax right for binding a non-sequential IDictionary<string, bool> object. Not sure this is 100% correct, but this Razor code worked for me:
<input type="hidden" name="MyDictionary.Index" value="ABC" />
<input type="hidden" name="MyDictionary[ABC].Key" value="ABC" />
#Html.CheckBox(name: "MyDictionary[ABC].Value", isChecked: Model.MyDictionary["ABC"], htmlAttributes: null)
If you need a checkbox, be sure to use Html.CheckBox instead of a standard HTML checkbox. The model will blow up if a value is not provided, and Html.CheckBox generates a hidden field to ensure a value is present when the checkbox is not checked.
Using Razor you can implement the for loop using a dictionary as follows without making changes to your object:
#foreach (var x in Model.Questions.Select((value,i)=>new { i, value }))
{
if (Model.Questions[x.i].QuestionType == "Single")
{
#Html.EditorFor(modelItem => (modelItem.Questions[x.i] as OpenDataPortal.ViewModels.SingleQuestionViewModel).AnswerText)
}
...
}
The collection needs to be either a List or Array for this to work.
I use this code maybe its can help
<input type="hidden" name="OffersCampaignDale[#(item.ID)].ID" value="#(item.ID)" />
#Html.Raw(Html.EditorFor(modelItem => item.NameDale, new { htmlAttributes = new { #class = "form-control" } })
.ToString().Replace("item.NameDale", "OffersCampaignDale[" + item.ID+ "].NameDale").Replace("item_NameDale", "NameDale-" + item.ID))
#Html.ValidationMessageFor(modelItem => item.NameDale, "", new { #class = "text-danger" })

When i set value of elements in editor template for grid pop up create , posting to controller as null

in my view there are two grid. when i select a row in first grid, second one is binding according to first one.
what i want to do is take common parameters from first one, used in second one create template in readonly or disabled inputs. my problem is input elements take parameter from first grid but, dont post to controller.
Controller Function
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult DonemKursSinifiOlustur([DataSourceRequest] DataSourceRequest request, DonemKursSinifi model,string DonemId, string DersId, string EgitmenId )
{
if (model != null && ModelState.IsValid)
{
Helper.Islemci.DonemKursSinifiTanimla(model);
}
return Json(new[] { model }.ToDataSourceResult(request, ModelState));
}
model.DonemId, model.DersId, model.EgitmenId and DonemId, DersId, EgitmenId come null.
EditorTemplate View for Grid Create and Update
#model Kurslar.Models.DonemKursSinifi
#using (Html.BeginForm("DonemKursSinifiOlustur","Tanim",FormMethod.Post))
{
<table>
<tr>
<td>
Lütfen Gün ve Saati Belirtiniz:
</td>
<td>
#Html.Kendo().AutoCompleteFor(m=>m.Tanim)
</td>
</tr>
<tr>
<td>
Donem :
</td>
<td>
#Html.Kendo().AutoCompleteFor(m=>m.DonemBaslangicBitis)
#Html.HiddenFor(m => m.DonemId)
</td>
</tr>
<tr>
<td>
Ders Adı:
</td>
<td>
#Html.Kendo().AutoCompleteFor(m=>m.DersAdi)
#Html.HiddenFor(m => m.DersId)
</td>
</tr>
<tr>
<td>
Eğitmen
</td>
<td>
#Html.Kendo().AutoCompleteFor(m=>m.EgitmenAdiSoyadi)
#Html.HiddenFor(m => m.DonemId)
</td>
</tr>
</table>}
First AutoCompleteFor works correctly because take input from user, not before setted.
*and my javaScript code to fill parameters to EditorTemplate *
and it works fine
var grid = $("#donemGrid").data("kendoGrid");
var rows = grid.select();
alert(rows);
try {
var donemID = grid.dataItem(rows).DonemId;
var dersID = grid.dataItem(rows).DersId;
var egitmenID = grid.dataItem(rows).EgitmenId;
var dersAdi = grid.dataItem(rows).DersAdi;
var egitmenAdiSoyadi= grid.dataItem(rows).EgitmenAdiSoyadi;
var donemBaslangicBitis = grid.dataItem(rows).DonemBaslangicBitis;
} catch (e) {
alert(e);
}
$("#DonemBaslangicBitis").data("kendoAutoComplete").value(donemBaslangicBitis);
$("#DersAdi").data("kendoAutoComplete").value(dersAdi);
$("#EgitmenAdiSoyadi").data("kendoAutoComplete").value(egitmenAdiSoyadi);
$("#DonemId").val(donemID);
$("#DersId").val(dersID);
$("#EgitmenId").val(egitmenID);
*if needed, my model *
public class DonemKursSinifi
{
[Key]
[Required]
[PersistentProperty(IsAutoIncremented = true)]
public int Id { get; set; }
[PersistentProperty]
public string Tanim { get; set; }
[PersistentProperty]
public int DonemId { get; set; }
[PersistentProperty]
public int DersId { get; set; }
[PersistentProperty]
public int EgitmenId { get; set; }
[PersistentProperty]
public int KontenjanSayisi { get; set; }
[PersistentProperty]
public int TarifeId { get; set; }
[PersistentProperty]
public int IslemNo { get; set; } // default 1
public string EgitmenAdiSoyadi { get; set; }
public string DersAdi { get; set; }
public string DonemBaslangicBitis { get; set; }
}
ok, probably you have repeated the id in the grid and also have the same name attributes in the same form to do this:
#Html.HiddenFor(m => m.DersId)
mabe you can do somethin like this:
form:
#model Kurslar.Models.DonemKursSinifi
#using (Html.BeginForm("DonemKursSinifiOlustur","Tanim", FormMethod.Post, new { id="myform"}))
{
<input type="hidden" value="" name="Tanim" />
<input type="hidden" value="" name="DonemBaslangicBitis" />
<input type="hidden" value="" name="DonemId" />
<input type="hidden" value="" name="DersAdi" />
<input type="hidden" value="" name="DersId" />
<input type="hidden" value="" name="EgitmenAdiSoyadi" />
<input type="hidden" value="" name="DonemId" />
}
table:
<table>
<tr>
<td>Lütfen Gün ve Saati Belirtiniz:</td>
<td>#Html.Kendo().AutoCompleteFor(m=>m.Tanim)</td>
</tr>
<tr>
<td>Donem :</td>
<td>#Html.Kendo().AutoCompleteFor(m=>m.DonemBaslangicBitis) #Html.HiddenFor(m => m.DonemId)</td>
</tr>
<tr>
<td>Ders Adı:</td>
<td>#Html.Kendo().AutoCompleteFor(m=>m.DersAdi) #Html.HiddenFor(m => m.DersId)</td>
</tr>
<tr>
<td>Eğitmen</td>
<td>#Html.Kendo().AutoCompleteFor(m=>m.EgitmenAdiSoyadi) #Html.HiddenFor(m => m.DonemId)</td>
</tr>
</table>
js:
var
grid = $("#donemGrid").data("kendoGrid"),
rows = grid.select(),
form = $('#myform');
form.find('input[name="DonemBaslangicBitis"]').val(grid.dataItem(rows).DonemBaslangicBitis);
form.find('input[name="DersAdi"]').val(grid.dataItem(rows).DersAdi);
form.find('input[name="EgitmenAdiSoyadi"]').val(grid.dataItem(rows).EgitmenAdiSoyadi);
form.find('input[name="DonemId"]').val(grid.dataItem(rows).DonemId);
form.find('input[name="DersId"]').val(grid.dataItem(rows).DersId);
form.find('input[name="EgitmenId"]').val(grid.dataItem(rows).EgitmenId);
form.submit();

show data from viewmodel in view

I tried this code but I have error like this:
The model item passed into the dictionary is of type
'System.Collections.Generic.List`1[XNet.Repository.Model.RoomType]',
but this dictionary requires a model item of type
'System.Collections.Generic.IEnumerable`1[XNet.Repository.Model.EditRoomTypeViewModel]'.
I don't know, whats part give an error. Please help.
my service
public List<EditRoomTypeViewModel> GetViewRoom(int RoomTypeID)
{
List<RoomType> roomTypes = (from d in _RoomTypeRepository.All()
select d).ToList();
List<EditRoomTypeViewModel> editRoomTypeViewModel = new List<EditRoomTypeViewModel>();
foreach (RoomType roomType in roomTypes)
{
editRoomTypeViewModel.Add(new EditRoomTypeViewModel
{
RoomTypeID = RoomTypeID,
RoomTypeName = roomType.RoomtypeName,
RoomTypeDescription = roomType.RoomTypeDescripton,
});
}
return editRoomTypeViewModel;
}
my controller
public ActionResult Room()
{
ViewBag.hotel = _hotelService.GetByID(2).HotelName;
List<EditRoomTypeViewModel> editRoomTypeViewModel = _roomViewService.GetViewRoom(_HotelID);
return View(editRoomTypeViewModel.FirstOrDefault());
}
my view model
public class EditRoomTypeViewModel
{
public int RoomTypeID { get; set; }
public string RoomTypeName { get; set; }
public string RoomTypeDescription { get; set; }
}
my view
#model IEnumerable<XNet.Repository.Model.EditRoomTypeViewModel>
#{
ViewBag.Title = "Room";
}
<h2>Room</h2>
<div>
#Html.Label("Hotel Name");
</div>
<div>
#ViewBag.hotel
</div>
<table>
#foreach (var a in Model)
{
<tr>
<td>
#Html.DisplayFor(model => a.RoomTypeName)
</td>
<td>
<input style="width:100px;" type="button" title="EditRoomType" value="Edit" onclick="location.href='#Url.Action("EditRoom", "Hotel", new { RoomTypeID = a.RoomTypeID})'" />
</td>
</tr>
}
</table>
<input style="width:200px;" type="button" title="EditRoomType" value="New Room Type" onclick="location.href='#Url.Action("NewRoom", "Hotel") '" />
I noticed that you returned just one editRoomTypeViewModel object in your controller, but in your view you declared the model as IEnumerable<XNet.Repository.Model.EditRoomTypeViewModel>.
Another point is that the error seems to be related to an assignment of ViewBag somewhere else, cause it contains thisdictionaryrequires a model item of type and probablt the only thing that is of type dictionary is ViewBag.
Just remove the .FirstOrDefault() in the controller action and you should be good to go.
public ActionResult Room()
{
ViewBag.hotel = _hotelService.GetByID(2).HotelName;
List<EditRoomTypeViewModel> editRoomTypeViewModel = _roomViewService.GetViewRoom(_HotelID);
return View(editRoomTypeViewModel);
}

Resources