Based on Darin's answer to my question Ho to display multiple checkbox selection based on user's selection from dropdown?
I am displaying multiple checkboxes based on dropdown selection.
Now, once the user post the form (with multiple inputs) that i have on my page, i collect all the data using FormCollection. And the problem i have is how can i pull those selected checkbox values from formcollection? The number of checkbox will change on different selection from the drop-down, so i think requesting each checkbox value will not work.
Can anyone help me with this problem.
The flow is as shown below:
Properties in Model
public class Subcategory
{
public string Name { get; set; }
public int ID { get; set; }
public bool Flag { get; set; }
}
Displaying PartialView in actual view where other form inputs are there:
<div id="checkboxlist">
#if (Model.SubCategories != null)
{
#Html.Partial("SubCategories", Model.SubCategories)
}
</div>
PartialView SubCategories.cshtml
#model IEnumerable<MyProject.Entities.Subcategory>
#{
// we change the HTML field prefix so that input elements
// such as checkboxes have correct names in order to be able
// to POST the values back
ViewData.TemplateInfo.HtmlFieldPrefix = "checkboxlist";
}
<span>subcategory</span>
<div id="subcategories" style="margin-left: 130px;margin-top: -20px;" data-role="fieldcontain">
<fieldset data-role="controlgroup">
#Html.EditorForModel()
</fieldset>
</div>
EditorTemplates Subcategory.cshtml
#model MyProject.Entities.Subcategory
<div class="editor-label">
#Html.CheckBoxFor(c => c.Flag, new { type = "checkbox" })
<label for="#Model.ID">#Model.Name</label>
#Html.HiddenFor(c => c.Flag)
#Html.HiddenFor(c => c.ID)
#Html.HiddenFor(c => c.Name)
</div>
jquery to display checkboxes based on dropdown selection:
$('#Category').change(function () {
var subcategoriesUrl = $(this).data('subcategoriesurl');
var categoryId = $(this).val();
$('#checkboxlist').load(subcategoriesUrl, { category: categoryId });
});
Don't use FormCollection. That's weakly typed. Use view models. Like this:
[HttpPost]
public ActionResult Foo(MyViewModel model)
{
// model.BusinessSubCategories should contain a list of Subcategory
// where for each element you could use the Flag property to see if
// it was selected or not
...
}
Also notice that you have an inconsistency between the field prefix that you are using in your partial:
ViewData.TemplateInfo.HtmlFieldPrefix = "checkboxlist";
and the view model collection property: Model.BusinessSubCategories. So make sure you fix the prefix to use the correct property name if you want the default model binder to be able to populate this property when you post back.
Related
I'm moving from WPF development to Asp MVC and have started doing an Asp MVC app. So far I've set up my:
model
controller
and
view(with the relevant fields.)
The next step involves sending the data entered in my form to the controller on the Submit button click.
I know in WPF I can bind the control properties to a property in the viewmodel, also there would be a click event on the button which I don't see in MVC.
This is my pseudo understanding of how to do that in MVC but correct me if I' wrong (Model is of type Case):
1.Set button click event to send form data to controller.
2.Pass data into controller constructor and assign to typed Case object.
Question:
How can you pass view values on button submit to a typed object in a controller?
Code:
View -
<form action="" method="post">
<div class="form-horizontal">
<div class="col-lg-6">
<!-- SELECT STATUS STATIC-->
<div class="form-group">
<label class="col-md-3 control-label" for="Current Status">Status</label>
<div class="col-md-8">
<select id="Status" name="Status" onchange="" class=" form-control">
<option value="Down">Down</option>
<option value="Up">Up</option>
</select>
</div>
</div>
<!-- SELECT APP STATIC-->
<div class="form-group">
<label class="col-md-3 control-label" for="App">App</label>
<div class="col-md-8" >
<select id="App" name="App" onchange="" class=" form-control">
<option value="SAP">SAP</option>
<option value="JAP">JAP</option>
</select>
</div>
</div>
<asp:Button id="b1" Text="Submit" runat="server" />
</div>
</div>
</form> <!--
Controller -
public class CaseController : Controller
{
public ActionResult Index()
{
return View();
}
}
Model -
Public class Case
{
public string Status { get; set; }
public string App { get; set; }
}
I hope that I understand your scenario well? You have a form with two drop down lists and a submit button? When you click the submit button you want to extract the selected values? This is how I understand it and this is how I will try to explain my answer with examples.
I would suggest that you bind your view/page to a view model. A view model is a kind of model that will represent your data in the view, whether it be textboxes, drop down lists, textareas, radio buttons, checkboxes, etc. It can also display static text on your view. I wrote a detailed answer as to what a view model is, if you have the time please go and read it:
What is ViewModel in MVC?
Go and create your view model. It will contain two lists that will represent your two drop down lists. Each list has an id associated with it that will contain the value of the selected drop down list item:
public class CaseViewModel
{
public int StatusId { get; set; }
public List<Status> Statuses { get; set; }
public int AppId { get; set; }
public List<App> Apps { get; set; }
}
Your domain models, namely Status and App, for the above mentioned lists:
public class Status
{
public int Id { get; set; }
public string Name { get; set; }
}
public class App
{
public int Id { get; set; }
public string Name { get; set; }
}
Now that you have this setup your next step is to populate these lists in your controller's action method. Ideally you would populate it with values from a database, but in your case I guess it is ok to hard code these values:
public ActionResult Index()
{
CaseViewModel model = new CaseViewModel();
model.Statuses = new List<Status>();
model.Statuses.Add(new Status { Id = 1, Name = "Down" });
model.Statuses.Add(new Status { Id = 2, Name = "Up" });
model.Apps = new List<App>();
model.Apps.Add(new App { Id = 1, Name = "SAP" });
model.Apps.Add(new App { Id = 2, Name = "JAP" });
return View(model);
}
As soon as you have populated your two lists, you pass the view model directly to the view. The view will receive a strongly type model and will do with it what it needs to do with it. In your case, a form will be created with two drop down lists and a submit button. I have left out all your CSS for clarity (just go and add it):
#model WebApplication_Test.Models.CaseViewModel
#using (Html.BeginForm())
{
<div>
#Html.DropDownListFor(
m => m.StatusId,
new SelectList(Model.Statuses, "Id", "Name", Model.StatusId),
"-- Select --"
)
#Html.ValidationMessageFor(m => m.StatusId)
</div>
<div>
#Html.DropDownListFor(
m => m.AppId,
new SelectList(Model.Apps, "Id", "Name", Model.AppId),
"-- Select --"
)
#Html.ValidationMessageFor(m => m.AppId)
</div>
<div>
<button type="submit">Submit</button>
</div>
}
So now you have two drop down lists populated with data. Select a value in each and press the submit button. Your view is bound to a view model and will retain values on form submission. Values in lists are not kept on form submission and will need to be populated again:
[HttpPost]
public ActionResult Index(CaseViewModel model)
{
// Check form validation
if (!ModelState.IsValid)
{
// If validation fails, rebind the lists and send the current view model back
model.Statuses = new List<Status>();
model.Statuses.Add(new Status { Id = 1, Name = "Down" });
model.Statuses.Add(new Status { Id = 2, Name = "Up" });
model.Apps = new List<App>();
model.Apps.Add(new App { Id = 1, Name = "SAP" });
model.Apps.Add(new App { Id = 2, Name = "JAP" });
return View(model);
}
// Form validation succeeds, do whatever you need to do here
return RedirectToAction("Index");
}
I hope this helps.
In the view just add a button in the form like
<button id="b1" Text="Submit"/>
In the controller add an action method to handle the post.
public class CaseController : Controller
{
[HttpPost]
public ActionResult Index(Case case)
{
//Do Something
return View();
}
public ActionResult Index()
{
return View();
}
}
You may also want to look into using Razor and strongly typed views. Makes things much simpler.
another approach is to use mvc ajax call, by doing these you also can pass parameter to controller from simple parameter to a selected row in gridview.
On the view in the button control add onclick property that point to a javascript function and passing parameter. In these sample will get selected row on the gridview
<input id="GenerateData" type="button" value="GenerateData" onclick="generateData(App.grdNameOfGridview.getRowsValues({selectedOnly:true}) [0]);" />
On the view create a javascript function that use ajax to call the controller, note the paramater that can be passing from click button event to the javascript function that will use ajax to call the controller. In this sample i use extjs framework, if you want you can also use jquery as well
generateData= function (recordData) {
var jsonStringContractUnit = JSON.stringify(recordData);
Ext.Ajax.request({
url: '../ControllerName/GenerateData',
method: 'POST',
params: {
SelectedContractUnit: jsonStringContractUnit
},
On the controller the parameter will be pass from view and will be store on SelectedData
public ActionResult GenerateData(string SelectedData)
{
}
Here are my view models:
public class UserViewModel
{
public User GroupUser { get; set; }
public bool Checked { get; set; }
}
public class GroupUserViewModel
{
public Guid GroupId { get; set; }
public string GroupName { get; set; }
public IList<UserViewModel> Users;
}
My view:
#model GroupUserViewModel
#{
ViewBag.Title = "Users";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>#Model.GroupName</h2>
#using (Html.BeginForm("AddUserToGroup", "Group", FormMethod.Post))
{
for (var userIter = 0; userIter < Model.Users.Count(); userIter++)
{
<div class="form-group">
#Html.DisplayFor(model => model.Users[userIter].GroupUser.UserName)
#Html.CheckBoxFor(model => model.Users[userIter].Checked)
#Html.HiddenFor(model => model.GroupId)
#Html.HiddenFor(model => model.GroupName)
</div>
}
<input type="submit" class="btn btn-success" value="Save"/>
}
My controller:
[HttpPost]
public ActionResult AddUserToGroup(GroupUserViewModel groupUsers)
{
//do things
}
I had an inspection of the POST data and it is:
Users[0].Checked=true
Users[0].Checked=false
Users[1].Checked=false
For the boxes I've ticked there are 2 entries, one true and one false. Is this normal?
Also in the controller, what I get back is:
groupUsers.GroupId = {00000000-0000-0000-0000-000000000000}
groupUsers.GroupName = null
groupUsers.Users = null
Obviously since the form isn't actually posting the view model I want back to the controller, this happens. Is there any way to pass the required view model back to the controller since I need the GroupId and GroupName?
EDIT:
After some updates and adding in hidden fields for GroupId and GroupName, now the POST data is:
Users[0].Checked=true
Users[0].Checked=false
Id=015f5aef-eb6c-449e-9f08-9d42110c5347
GroupName=MyName
MyObjects[1].Checked=false
Id=015f5aef-eb6c-449e-9f08-9d42110c5347
GroupName=MyName
The GroupId and GroupName are now being passed corrently but the list is still null.
Yes this is normal. The reason is because an unchecked checkbox will not post a value, so ASP.NET renders a hidden field for every checkbox with the same ID as the checkbox just after the checkbox control, and sets its value to false. ASP.NET DefaultModelBinder will, if there are multiple form fields with the same name, take the first value. This results in one value of false being posted from the hidden field if the checkbox is not checked, and two values, one of false for the hidden field and one of true for the checked checkbox. Because the hidden field comes after the checkbox, if the checkbox posts a value, it will override the hidden field.
However, that doesn't answer your question as to why the model isn't binding..
IList<UserViewModel> Users in GroupUserViewModel is a field, not a property so the DefaultModelBinder cannot set its value. Change it to
public class GroupUserViewModel
{
....
public IList<UserViewModel> Users { get; set; } // make it a property
}
I have a DropDownListFor control that I am wanting to show a display value that resides in a property within a model/class (this is the Rule class.) The view's model is actually a collection of these model/classes. However, when I select the item from the DropDownList, I want to send back the entire model as a parameter. I have this working perfectly with the following code, but the Name property within the parameter is coming back as null. The other properties all have appropriate values.
View Code:
#model List<StockTrader.Web.Data.Rule>
#{
ViewBag.Title = "Configure Rules";
}
<h2>#ViewBag.Title</h2>
<h4>Choose a rule to edit:</h4>
<form method="post" id="rulesform" action="SaveRules">
#Html.DropDownListFor(m => m.First().RuleID, new SelectList(Model.AsEnumerable(), "RuleID", "Name"))
<div style="margin-bottom: 15px;">
<label>Value:</label><br />
<input type="number" name="Value" style="margin-bottom: 15px;" /><br />
<button>Save Value</button>
</div>
Controller Code:
public ActionResult SaveRules(Rule model)
{
//do something
}
Rule Class:
public class Rule
{
public int RuleID { get; set; }
public string Name { get; set; }
public int Value { get; set; }
public bool IsDeleted { get; set; }
}
We do have Kendo controls, so if another control would be more appropriate, that is an option.
I would be glad to provide anymore code or information you might need.
Any thoughts or ideas?
EDIT:
So it turns out this is what I needed to do, the accepted answer got me to this point so I'm going to leave it checked.
View Code (w/script included):
#Html.DropDownListFor(m => m.First().RuleID, new SelectList(Model.AsEnumerable(), "RuleID", "Name"), new { id = "ruleid", #onchange = "CallChangefunc(this)" })
#Html.HiddenFor(m => m.First().Name, new { id = "rulename" })
function CallChangefunc(e) {
var name = e.options[e.selectedIndex].text;
$("#rulename").val(name);
}
You will need a hidden field for it,and use dropdownlist on change event on client side to update hidden field:
#Html.DropDownListFor(m => m.First().RuleID, new SelectList(Model.AsEnumerable(), "RuleID", "Name"),new { id= "ruleid" })
#Html.HiddenFor(m=>m.First().Name,new { id="rulename" })
and jquery code:
$("#ruleid").change(function(){
$("#rulename").val($(this).text());
});
Second option isif Rule collection is coming from database you can fetch RuleName by using id to by querying db in action.
it can be achieved by using UIHint
On your model class, on the RuleID property, add an annotation for UIHint. It basically lets you render a partial (cshtml) for the property. So, on the partial, you can have the template for generating the dropdwon with required styling. When Page is generated. Now you can use the same Html.DropDownListFor for RuleID and UI generates a dropdown for it.
This will avoid having additional jQuery code to get the dropdown value, and code is more concise and testable.
I have a dropdown list rendered from a database, just need to be able to set an existing value (if it exists). _jobService.GetTenancyForJob gets a value if one already exists and the other service just returns an id and value for each item. I need to be able to set the selected list item here in the controller but just struggling with the syntax (yeah it's using viewbag just for testing will be using ViewModel).
I've done this before in a wide variety of ways just wondering how it would be done in this scenario... Any pointers appreciated.
var jobTenancies = _jobService.GetTenancyForJob(id);
var getTenancies = _jobService.GetAllJobTenancies();
var tenancyList = getTenancies.Select( t => new SelectListItem()
{
Text = t.JobTenancyName,
Value = t.Id.ToString()
}).ToList();
tenancyList.Insert(0, new SelectListItem() { Text="", Value = "" } );
Viewbag.TenancyList = tenancyList;
Edit: in the view
<div class="control-group">
#Html.BootstrapLabelFor(model => model.TenancyName)
<div class="controls">
#Html.DropDownListFor(x=>x.TenancyId, (List<SelectListItem>)ViewBag.TenancyList)
#Html.BootstrapValidationMessageFor(model => model.TenancyId)
</div>
</div>
You need to set the value of property TenancyId in the controller before you return the View. If the value matches the value of one of your options then that option will be selected when the view is displayed. Note also you should not be adding a 'empty' option by inserting an additional SelectListItem (which adds <option value="">), but rather use the overload of DropDownListFor() that accepts optionLabel which correctly adds an option with a null value (<option value>). As you indicated you intend to use a view model, it might include
public class TenancyVM
{
[Required(ErroMessage = "Please select tenancy")]
[Display(Name = "Tenancy")]
public int? TenancyID { get; set; }
....
public SelectList TenancyList { get; set; }
}
Controller
public ActionResult Edit(int id)
{
TenancyVM model = new TenancyVM();
model.TenancyID = jobService.GetTenancyForJob(id);
ConfigureEditModel(model);
return View(model);
}
// Gets called in the GET and in POST method if the view is returned
private void ConfigureEditModel(TenancyVM model)
{
var tenancies = _jobService.GetAllJobTenancies();
model.TenancyList = new SelectList(tenancies , "Id", "JobTenancyName");
}
View
<div class="control-group">
#Html.BootstrapLabelFor(m => m.TenancyID)
<div class="controls">
#Html.DropDownListFor(m => m.TenancyID, Model.TenancyList, "-Please select-")
#Html.BootstrapValidationMessageFor(m => m.TenancyID)
</div>
</div>
You need to cast your ViewBag data to SelectList as follow:
var data = (SelectList)Viewbag.TenancyList;
You need to do this because ViewBag carry object data type.
After casting you can get your tenacyList from data.Items.
I have this web page which shows the property of an object so that I may edit it, and I populate a DropDownListwith strings coming from another class.
Here's the method I use to populate the DropDownList:
private void PopulateOBJSetDropdownList(object selectedobj = null)
{
List<string> listOBJSetName = m_OBJSetManager.GetListOBJSets().OrderBy(x => x.m_Name)
.Select(x => x.m_Name.ToString())
.Distinct()
.ToList();
ViewBag.objSetID = new SelectList(listOBJSetName );
}
The ViewBagproperty does its job quite well, but the list comes empty when editing the item.
I'm pretty sure it is because of this line:
<div class="editor-label">
#Html.LabelFor(model => model.m_OBJSetID, "Obj Set")
</div>
<div class="editor-field">
#Html.DropDownList("objSetID ", String.Empty)
#Html.ValidationMessageFor(model => model.m_OBJSetID)
</div>
Because the dropdownlist is populated with String.Empty. This comes from a controller of objs.
Basically, I want this DropDownList to show me all the names of the objSets available, but I would also want it to have the correct objSet selected by default when editing an obj.
Does anyone can help? Am I clear enough? Thank you everyone.
i would avoid the viewbag. you might want to create a view model, and pass that instead.
but this can be done with the viewbag as well.
first, on your view, i would change your dropdown to the following
#Html.DropDownListFor(model => model.m_OBJSetID, DDLSelectitemListGoesHere)
if you do a view model, you can contain everything this page needs to use in one class, and send it to the view
public class MyViewModel{
public List<YourModel> theModel { get; set; }
public IEnumerable<SelectListItem> DDLItems { get; set; }
}
then on your view, at the top
#model PROJECTNAME.NAMESPACE.MyViewModel
and you can fill in the drop down like so
#Html.DropDownListFor(model => model.theModel.m_OBJSetID, model.DDLItems)
hopefully one of those will get you through