MVC3 Can't get model back to the controller - asp.net-mvc-3

I have the following ViewModel
public class RecommendationModel
{
public List<CheckBoxItem> CheckBoxList { get; set; }
}
public class CheckBoxItem
{
public string Text { get; set; }
public bool Checked { get; set; }
public string Link { get; set; }
}
With the following View
model Sem_App.Models.RecommendationModel
#using (Html.BeginForm())
{
for (int i = 0; i < Model.CheckBoxList.Count(); i++) {
#Html.CheckBoxFor(m => m.CheckBoxList[i].Checked)
#Html.DisplayFor(m => m.CheckBoxList[i].Text)
}
<input type="submit" value="Add To Playlist" />
}
With the following controller actions
//get
public ActionResult Recommendation()
{
RecommendationModel model = new RecommendationModel();
model.CheckBoxList = new List<CheckBoxItem>();
return PartialView(model);
}
//post
[HttpPost]
public ActionResult Recommendation(RecommendationModel model)
{
foreach (var item in model.CheckBoxList)
{
if (item.Checked)
{
// do something with item.Text
}
}
}
Problem is whenever I select some items and press the submit button the model returned has CheckBoxList as empty. How can I change my view to return the list of CheckBoxList? Trying
#Html.HiddenFor(m => m.checkBoxList) did not work for me

I think you nee something like this
#using (Html.BeginForm())
{
for (int i = 0; i < Model.CheckBoxList.Count(); i++) {
#Html.CheckBoxFor("Model.CheckBoxItem[" + i + "].Checked" , m => m.CheckBoxList[i].Checked)
#Html.DisplayFor("Model.CheckBoxItem[" + i + "].Text",m => m.CheckBoxList[i].Text)
}

Try adding the link as a hidden field: #Html.HiddenFor(m => m.CheckBoxList[i].Link )

Check how the checkbox input name is in the rendered html and also check the form action is sending to the corrent controller/action and the method is post
it should be something very simple.. create the action param as array with the same name of the "name" attribute form check box input
something like this
[HttpPost]
public ActionResult Delete(int[] checkName)
{
}

Related

Passing null values to the parameter in controller after submit?

The below code is sample I typed
After I submit passing null values to controller, In Controller I have used the Class name then value passing correctly but when i used the parameter it passing NULL values to the controller. Please give me a solution..
Controller:
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string firstname)
{
LogonViewModel lv = new LogonViewModel();
var ob = s.Newcustomer(firstname)
return View(ob );
}
View:
#model IList<clientval.Models.LogonViewModel>
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm())
{
for (int i = 0; i < 1; i++)
{
#Html.LabelFor(m => m[i].UserName)
#Html.TextBoxFor(m => m[i].UserName)
#Html.ValidationMessageFor(per => per[i].UserName)
<input type="submit" value="submit" />
}
}
Model:
public class LogonViewModel
{
[Required(ErrorMessage = "User Name is Required")]
public string UserName { get; set; }
}
public List<ShoppingClass> Newcustomer(string firstname1)
{
List<ShoppingClass> list = new List<ShoppingClass>();
..
}
This:
[HttpGet]
public ActionResult Index() {
return View();
}
Does not give you this in your view:
#model IList<clientval.Models.LogonViewModel>
And this:
for (int i = 0; i < 1; i++) {
#Html.LabelFor(m => m[i].UserName)
#Html.TextBoxFor(m => m[i].UserName)
#Html.ValidationMessageFor(per => per[i].UserName)
<input type="submit" value="submit" />
}
Will not work with this:
[HttpPost]
public ActionResult Index(string firstname) {
LogonViewModel lv = new LogonViewModel();
var ob = s.Newcustomer(firstname)
return View(ob );
}
You're not sending a model to your view, and you're using a list in your view, but expecting a single string value in you controller. Something is very strange/wrong with your example, or your code.
Why do you have a IList as your model? If all you need is to render a form with a single input field. You should have code like this:
[HttpGet]
public ActionResult Index() {
return View(new LogonViewModel());
}
And the view:
#model clientval.Models.LogonViewModel
#using (Html.BeginForm())
{
#Html.LabelFor(m => m.UserName)
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
<input type="submit" value="submit" />
}
And the second action on the controller:
[HttpPost]
public ActionResult Index(LogonViewModel model) {
if (ModelState.IsValid) {
// TODO: Whatever logic is needed here!
}
return View(model);
}
Its working.. I have changed my controller as written below
Controller:
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(IList<LogonViewModel> obj)
{
LogonViewModel lv = new LogonViewModel();
var ob = lv.Newcustomer(obj[0].FirstName)
return View(ob );
}

DropDownListFor in MVC3

OK first of all, am new to ASP.NET MVC. Now i am trying to add a dropdown list in a C# Razor view.
Question is, is there anyway to directly assign List() to the #Html.DropDownListFor...?
MyClass goes like this
public class MyClass
{
public int ID {get; set;}
public string Itemstring {get; set;}
}
ViewModel goes like this
public class MyViewModel
{
public int ID { get; set; }
public List<MyClass> MyClassList {get; set; }
}
Controller action method goes like this
public ActionResult Home()
{
MyViewModel mvm = new MyViewModel () {
new MyClass() { ID=1, Itemstring="My Item1" },
new MyClass() { ID=2, Itemstring="My Item2" },
new MyClass() { ID=3, Itemstring="My Item3" }
}
}
On View: THIS IS WHERE I AM NOT SURE HOW TO USE
#model xyzNameSpace.Models.MyViewModel
<div>
#Html.DropDownListFor(x => x.ID, Model.MyClassList);
<a href="#Url.Action("Selected")><img src="../../Content/images/selected.gif" alt="Proceed" /> </a>
</div>
-- So when user selects one item from dropdown and clicks on image, it should invoke (or call not sure which word to use) 'Selected' action in the control and it should bind the model with selected value, Could some one help me how to do this...?
Thank you
Siri.
Html.DropDownListFor has 6 overloads and all of them take IEnumerable<SelectListItem> as the parameter that will hold your values. You cannot dirrecly use your own class for that, which is why you get that error when you tried solution by Kyle.
Add this to your model:
public List<SelectListItem> ListToUse { get; set; }
Controller:
MyViewModel model = new MyViewModel();
model.MyClassList = new List<MyClass>
{
new MyClass() { ID=1, Itemstring="My Item1" },
new MyClass() { ID=2, Itemstring="My Item2" },
new MyClass() { ID=3, Itemstring="My Item3" }
}
model.ListToUse = model.MyClassList
.Select(x => new SelectListItem{ Value = x.ID, Text = x.Itemstring })
.ToList();
In the view:
#Html.DropDownListFor(x => x.ID, Model.ListToUse);
I did not test this code.
If I understand you correctly, you want to post the selected item from the dropdownlist to the server when the "Proceed" button is clicked?
You will need to use a form to do this:
#model xyzNameSpace.Models.MyViewModel
#using(Html.BeginForm())
{
<div>
#Html.DropDownListFor(x => x.ID, Model.MyClassList);
<input type="submit" value="Proceed" />
</div>
}
in model
public class modelname
{
public selectlist getdropdown()
{
IEnumerable<SelectListItem> EntityList = edmx.tblEntities.AsEnumerable().Select(a => new SelectListItem { Text = a.name, Value = a.id.ToString() }).ToList();
return new SelectList(EntityList, "Value", "Text");
}
}
in view
#Html.DropDownListFor(model => model.source_entity, Model.getdropdown(), "--Select--")
in contoller
public ActionResult home()
{
return View(new modelname());
}

To populate a dropdown in mvc3

I am new to MVC3
I am finding it difficult to create an dropdown.I have gone through all the other related questions but they all seem to be complex
I jus need to create a dropdown and insert the selected value in database
Here is what i have tried:
//Model class:
public int Id { get; set; }
public SelectList hobbiename { get; set; }
public string filelocation { get; set; }
public string hobbydetail { get; set; }
//Inside Controller
public ActionResult Create()
{
var values = new[]
{
new { Value = "1", Text = "Dancing" },
new { Value = "2", Text = "Painting" },
new { Value = "3", Text = "Singing" },
};
var model = new Hobbies
{
hobbiename = new SelectList(values, "Value", "Text")
};
return View();
}
//Inside view
<div class="editor-label">
#Html.LabelFor(model => model.hobbiename)
</div>
<div class="editor-field">
#Html.DropDownListFor( x => x.hobbiename, Model.hobbiename )
#Html.ValidationMessageFor(model => model.hobbiename)
</div>
I get an error:System.MissingMethodException: No parameterless constructor defined for this object
You are not passing any model to the view in your action. Also you should not use the same property as first and second argument of the DropDownListFor helper. The first argument that you pass as lambda expression corresponds to a scalar property on your view model that will hold the selected value and which will allow you to retrieve this value back when the form is submitted. The second argument is the collection.
So you could adapt a little bit your code:
Model:
public class Hobbies
{
[Required]
public string SelectedHobbyId { get; set; }
public IEnumerable<SelectListItem> AvailableHobbies { get; set; }
... some other properties that are irrelevant to the question
}
Controller:
public class HomeController: Controller
{
public ActionResult Create()
{
// obviously those values might come from a database or something
var values = new[]
{
new { Value = "1", Text = "Dancing" },
new { Value = "2", Text = "Painting" },
new { Value = "3", Text = "Singing" },
};
var model = new Hobbies
{
AvailableHobbies = values.Select(x => new SelectListItem
{
Value = x.Value,
Text = x.Text
});
};
return View(model);
}
[HttpPost]
public ActionResult Create(Hobbies hobbies)
{
// hobbies.SelectedHobbyId will contain the id of the element
// that was selected in the dropdown
...
}
}
View:
#model Hobbies
#using (Html.BeginForm())
{
#Html.LabelFor(x => x.SelectedHobbyId)
#Html.DropDownListFor(x => x.SelectedHobbyId, Model.AvailableHobbies)
#Html.ValidationMessageFor(x => x.SelectedHobbyId)
<button type="submit">Create</button>
}
I would create them as
Model:
public class ViewModel
{
public int Id { get; set; }
public string HobbyName { get; set; }
public IEnumerable<SelectListItem> Hobbies {get;set; }
public string FileLocation { get; set; }
public string HobbyDetail { get; set; }
}
Action
public ActionResult Create()
{
var someDbObjects= new[]
{
new { Id = "1", Text = "Dancing" },
new { Id = "2", Text = "Painting" },
new { Id = "3", Text = "Singing" },
};
var model = new ViewModel
{
Hobbies = someDbObjects.Select(k => new SelectListItem{ Text = k, Value = k.Id })
};
return View(model);
}
View
<div class="editor-label">
#Html.LabelFor(model => model.HobbyName)
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.HobbyName, Model.Hobbies )
#Html.ValidationMessageFor(model => model.HobbyName)
</div>

MVC3 dropdown list that displays mutliple properties per item

I want to have a dropdownlist in my view that displays a patient's ID, First Name, and Last Name. With the code below, it displays each patient's First Name. How can I pass all three properties into the viewbag and have them display in the dropdownlist?
Controller
public ActionResult Create()
{ViewBag.Patient_ID = new SelectList(db.Patients, "Patient_ID", "First_Name");
return View();
}
View
<div class="editor-field">
#Html.DropDownList("Patient_ID", String.Empty)
#Html.ValidationMessageFor(model => model.Patient_ID)
</div>
Thanks.
Ok, I have edited my code as follows, and I receive the error "There is no ViewData item of type 'IEnumerable' that has the key 'SelectedPatientId'."
Controller
public ActionResult Create()
{
var model = new MyViewModel();
{
var Patients = db.Patients.ToList().Select(p => new SelectListItem
{
Value = p.Patient_ID.ToString(),
Text = string.Format("{0}-{1}-{2}", p.Patient_ID, p.First_Name, p.Last_Name)
});
var Prescribers = db.Prescribers.ToList().Select(p => new SelectListItem
{
Value = p.DEA_Number.ToString(),
Text = string.Format("{0}-{1}-{2}", p.DEA_Number, p.First_Name, p.Last_Name)
});
var Drugs = db.Drugs.ToList().Select(p => new SelectListItem
{
Value = p.NDC.ToString(),
Text = string.Format("{0}-{1}-{2}", p.NDC, p.Name, p.Price)
});
};
return View(model);
}
View Model
public class MyViewModel
{
[Required]
public int? SelectedPatientId { get; set; }
public IEnumerable<SelectListItem> Patients { get; set; }
[Required]
public int? SelectedPrescriber { get; set; }
public IEnumerable<SelectListItem> Prescribers { get; set; }
[Required]
public int? SelectedDrug { get; set; }
public IEnumerable<SelectListItem> Drugs { get; set; }
}
View
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
#Html.DropDownListFor(
x => x.SelectedPatientId,
Model.Patients,
"-- Select patient ---"
)
#Html.ValidationMessageFor(x => x.SelectedPatientId)
<button type="submit">OK</button>
#Html.DropDownListFor(
x => x.SelectedPrescriber,
Model.Patients,
"-- Select prescriber ---"
)
#Html.ValidationMessageFor(x => x.SelectedPrescriber)
<button type="submit">OK</button>
}
I would recommend you not to use any ViewBag at all and define a view model:
public class MyViewModel
{
[Required]
public int? SelectedPatientId { get; set; }
public IEnumerable<SelectListItem> Patients { get; set; }
}
and then have your controller action fill and pass this view model to the view:
public ActionResult Create()
{
var model = new MyViewModel
{
Patients = db.Patients.ToList().Select(p => new SelectListItem
{
Value = p.Patient_ID.ToString(),
Text = string.Format("{0}-{1}-{2}", p.Patient_ID, p.First_Name, p.Last_Name)
});
};
return View(model);
}
and finally in your strongly typed view display the dropdown list:
#model MyViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(
x => x.SelectedPatientId,
Model.Patients,
"-- Select patient ---"
)
#Html.ValidationMessageFor(x => x.SelectedPatientId)
<button type="submit">OK</button>
}
Easy way to accomplish that is just creating additional property on your model either by modifying model class or adding/modifying a partial class
[NotMapped]
public string DisplayFormat
{
get
{
return string.Format("{0}-{1}-{2}", Patient_ID, First_Name, Last_Name);
}
}

Nested EditorTemplates in Telerik MVC Grid Edit Popup Window Not Displaying in Custom Edit Template

I have a grid using AJAX DATABINDING.
When I issue a POPUP EDITING command with TEMPLATENAME SPECIFIED my NESTED EDITOR TEMPLATES are not populating.
My Models
namespace eGate.BackOffice.WebClient.Model
{
public class TemplateTesterModel
{
public int TemplateModelId { get; set; }
public string TemplateModelName { get; set; }
public List<UserRole> UserRoles { get; set; }
}
}
{
public class TemplateTesterModels : List<TemplateTesterModel>
{
}
}
My View
#model eGate.BackOffice.WebClient.Model.TemplateTesterModels
#Html.EditorFor(m=>m)
#( Html.Telerik().Grid<eGate.BackOffice.WebClient.Model.TemplateTesterModel>()
.Name("Grid")
.DataKeys(keys => { keys.Add(m=>m.TemplateModelId); })
.Columns(columns =>
{
columns.Bound(o => o.TemplateModelId);
columns.Bound(o => o.TemplateModelName).Width(200);
columns.Bound(o => o.UserRoles).ClientTemplate(
"<# for (var i = 0; i < UserRoles.length; i++) {" +
"#> <#= UserRoles[i].RoleName #> <#" +
"} #>")
;
columns.Command(commands =>
{
commands.Edit().ButtonType(GridButtonType.Text);
}).Width(180).Title("Commands");
})
.DataBinding(dataBinding => dataBinding.Ajax()
.Select("_SelectAjaxEditing", "TemplateTester")
.Insert("_InsertAjaxEditing", "Grid")
.Update("_SaveAjaxEditing", "TemplateTester")
.Delete("_DeleteAjaxEditing", "TemplateTester")
)
.Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("TemplateTesterModel"))
)
My Controller
namespace eGate.BackOffice.WebClient.Controllers
{
public class TemplateTesterController : Controller
{
public ActionResult Index()
{
return View(GetTemplateTesters());
//return View(new GridModel(GetTemplateTesters()));
}
private TemplateTesterModels GetTemplateTesters() {
TemplateTesterModels returnme = new TemplateTesterModels();
returnme.Add(new TemplateTesterModel());
returnme[0].TemplateModelId = 0;
returnme[0].TemplateModelName = "Template Tester 0";
returnme[0].UserRoles = new List<UserRole>();
returnme[0].UserRoles.Add(new UserRole() { RoleName = "Role1", IsChecked = true, Description = "Role for 1" });
returnme[0].UserRoles.Add(new UserRole() { RoleName = "Role2", IsChecked = false, Description = "Role for 2" });
returnme[0].UserRoles.Add(new UserRole() { RoleName = "Role3", IsChecked = false, Description = "Role for 3" });
return returnme;
}
[GridAction]
public ActionResult _SelectAjaxEditing()
{
return View(new GridModel(GetTemplateTesters()));
}
[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult _SaveAjaxEditing(int id)
{
return View(new GridModel(GetTemplateTesters()));
}
[GridAction]
public ActionResult _InsertAjaxEditing(){
return View(new GridModel(GetTemplateTesters()));
}
[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult _DeleteAjaxEditing(int id)
{
return View(new GridModel(GetTemplateTesters()));
}
}
}
My EditorTemplates
Shared/EditorTemplates/TemplateTesterModel.cshtml
#model eGate.BackOffice.WebClient.Model.TemplateTesterModel
<div>TemplateTesterModel Editor</div>
<div>#Html.EditorFor(m=>m.TemplateModelId)</div>
<div>#Html.EditorFor(m=>m.TemplateModelName)</div>
<div>Roles</div>
<div>#Html.EditorFor(m=>m.UserRoles)</div>
Shared/EditorTemplates/UserRole.cshtml
#model eGate.BackOffice.WebClient.Model.UserRole
<div>
I can has user role?
#Html.CheckBoxFor(m=>m.IsChecked)
</div>
This renders out as such:
As you can see the #Html.EditFor statements that precede the grid filter down through to the userrole EditorTemplate as expected. Additionally we can see that role data is in the grid because it is showing up in the role column.
But click the edit window and this is the result:
As you can see the UserRoles template is not populating with the roles on the UserRoles property of the TemplateTesterModel we're editing.
Am I missing something? Why is the .UserRoles property not populating in the telerik grid pop-up window?
This could be a "by design" decision of ASP.NET MVC. It does not automatically render display and editor templates for nested complex objects. I even have a blog post discussing this.
Long story short you need to create a custom editor template for the parent model.

Resources