How to get checkbox row value selected in Grid.MVC - asp.net-mvc

Hi I have included Grid.MVC in asp .net mvc 4 i am able to display the
checkbox in grid but how do i get to know the particular checkbox is
selected in a row since i want to post it to the server and check it
at the controller end Below is the code any advice regarding are
welcome and is there any way i can place a checkbox for header
#Html.Grid(Model).Columns(columns =>
{
columns.Add().Encoded(false).Sanitized(false).SetWidth(10).RenderValueAs(o => Html.CheckBox("checked", false));
columns.Add().Encoded(false).Sanitized(false).Titled("Headline").SetWidth(220).RenderValueAs(news => #Html.ActionLink(news.HeadLine, "Details", new { Id = news.Id }));
columns.Add(news => news.Time).Titled("News Time").SetWidth(110).Sortable(true).Filterable(true);
}).WithPaging(20)

Sorry for the late reply, but today I found my self with the same question.
The following code will work as you want:
columns.Add()
.Encoded(false)
.Sanitized(false)
.SetWidth(10)
.RenderValueAs(o => Html.CheckBox("checked", o.YourModelBoolProperty));
Good luck.

Add value attribute to the checkboxes, set their value as news.Id (if news.Id is the primary key or unique else set some value by which you will be able to identify the checked rows in controller).
Add the name attribute to the checkboxes and give same name to all of them.
Html.CheckBox("checked", false, new {name = "assignChkBx"})
Use a action in controller with form colection object to get the checkbox values
public void Controls(FormCollection form)
You will get only those values in FormCollection which are checked.
var checkBox = form.GetValues("assignChkBx");
if (checkBox != null)
{
foreach (var id in checkBox)
{
}
}

columns.Add().Titled("").Encoded(false).Sanitized(false).RenderValueAs(o => Html.CheckBox(string.Format("ArrayProperty[{0}].Selected", Model.ArrayProperty.IndexOf(o)), o.Selected));
Works for me - and a little bit cleaner than the other answer. For some reason I can't get the other item posted to work

Related

In Asp.net MVC Razor Radiobutton, how to assign variable to name?

I have multiple radio button groups on my razor cshtml page. I need to specify the name as a variable because each group needs to have it's own unique radio button choice. Basically I have what is below that does not work. that is, workshopDay does not appear to be being interpreted as a variable.
#foreach (var workshopDay in new List<string> {"Wednesday", "Thursday"})
...
#Html.RadioButtonFor(a => a.AngularUsignup.AttendeeParty,
new { #class = "radio",#name="#(workshopDay)" })
try following.
#foreach (var workshopDay in new List<string> {"Wednesday", "Thursday"})
...
#Html.RadioButtonFor(a => a.AngularUsignup.AttendeeParty,
new { #class = "radio",#name=workshopDay.ToString() })
Note: As Stephen mentioned in comment to question it will allow all radio button to be selected. Instead you should use checkbox in such a scenarios.
This is one of those gotcha's:
To override the name attribute (or one of the other attributes that the HtmlHelper adds for you) you need to use the attribute name with the first letter upper-cased (so: "Name" rather than "name"):
#Html.RadioButtonFor(a => a.SomeProperty, new { Name="yourValuehere" })
So, I think your example goes to:
#Html.RadioButtonFor(a => a.AngularUsignup.AttendeeParty,
new { #class = "radio",#Name="#(workshopDay)" })
HTH

Retrieving Data of a combobox item -Telerik MVC

my application is asp.net MVC, I am using Telerik MVC Combobox, using ViewData, I send items as:
people.Add(new Person { Id = 1, Name = "John", viewed = true });
<% Html.Telerik().ComboBox()
.Name("ComboBox")
.BindTo(new SelectList((IEnumerable<Person>)ViewData["people"], "Id", "Name"))
.ClientEvents(events => events.OnChange("ComboBox_onChange")
.OnLoad("ComboBox_onLoad")
.OnOpen("ComboBox_OnOpen"))
.Render();
%>
I can get the text of a specific item using:
var item = combobox.dropDown.$items.eq(0);
alert(item.text());
Any idea how I can get the data of this item to check if the value of viewed if it is true of false.
I tried:
alert(item.Value.split('|'));
but got this error: Unable to get value of the property 'split': object is null or undefined
Thanks in advance.
Here is the Client API documentation
Basically you need to get a reference to the combobox plugin first:
var combo = $('#ComboBox').data('tComboBox');
Then you can call whatever method you need:
alert( combo.value() );
EDIT:
Your combobox is currently bound to a SelectList where the Value is Person.Id and Text is Person.Name. The "viewed" property is not stored anywhere. You could include it as part of the Value, retrieve the value as I described above, and then split() to get the "viewed" part:
Html.Telerik().ComboBox()
.Items(items =>
{
// pseudo-code
foreach (person)
items.Add().Text(person.Name).Value(person.Id + "_" + person.Viewed)
})
...

Dropdownlist post in ASP.NET MVC3 and Entity Framework Model

I have 3 tables:
RateProfile
RateProfileID
ProfileName
Rate
RateID
RateProfileID
PanelID
Other stuff to update
Panel
PanelID
PanelName
I have models for each of these. I have an edit page using the RateProfile model. I display the information for RateProfile and also all of the Rates associated with it. This works fine and I can update it fine. However, I also added a dropdown so that I can filter Rates by PanelID. I need it to post back on change so that it can display the filtered rates.
I'm using
#Html.DropDownList("PanelID", (SelectList)ViewData["PanelDropDown"], new { onchange = "$('#RateForm').submit()" })
for my dropdownlist. Whenever it posts back to my HttpPost Edit method though, it seems to be missing all information about the Rates navigation property. It's weird because I thought it would do exactly what the input/submit button that I have in the form does (which actually passes the entire model back to my HttpPost Edit action and does what I want it to do). The panelID is properly being passed to my HttpPost Edit method and on to the next view, but when I try to query the Model.Rates navigation property is null (only when the post comes from the dropdown. Everything works fine when the post comes from my submit input).
Get Edit:
public ActionResult Edit(int id, int panelID = 1)
{
RateProfile rateprofile = db.RateProfiles.Single(r => r.RateProfileID == id);
var panels = db.Panels;
ViewData["PanelDropDown"] = new SelectList(panels, "PanelID", "PanelName", panelID);
ViewBag.PanelID = panelID;
return View(rateprofile);
}
HttpPost Edit:
[HttpPost]
public ActionResult Edit(RateProfile rateprofile, int panelID)
{
var panels = db.Panels;
ViewData["PanelDropDown"] = new SelectList(panels, "PanelID", "PanelName", panelID);
ViewBag.PanelID = panelID;
if (ModelState.IsValid)
{
db.Entry(rateprofile).State = EntityState.Modified;
foreach (Rate dimerate in rateprofile.Rates)
{
db.Entry(dimerate).State = EntityState.Modified;
}
db.SaveChanges();
return View(rateprofile);
}
return View(rateprofile);
}
View:
#model PDR.Models.RateProfile
#using (Html.BeginForm(null,null,FormMethod.Post, new {id="RateForm"}))
{
<div>
#Html.Label("Panel")
#Html.DropDownList("PanelID", (SelectList)ViewData["PanelDropDown"], new { onchange = "$('#RateForm').submit()" })
</div>
#{var rates= Model.Rates.Where(a => a.PanelID == ViewBag.PanelID).OrderBy(a => a.minCount).ToList();}
#for (int i = 0; i < rates.Count; i++)
{
<tr>
<td>
#Html.HiddenFor(modelItem => rates[i].RateProfileID)
#Html.HiddenFor(modelItem => rates[i].RateID)
#Html.HiddenFor(modelItem => rates[i].PanelID)
#Html.EditorFor(modelItem => rates[i].minCount)
#Html.ValidationMessageFor(model => rates[i].minCount)
</td>
<td>
#Html.EditorFor(modelItem => rates[i].maxCount)
#Html.ValidationMessageFor(model => rates[i].maxCount)
</td>
<td>
#Html.EditorFor(modelItem => rates[i].Amount)
#Html.ValidationMessageFor(model => rates[i].Amount)
</td>
</tr>
}
<input type="submit" value="Save" />
}
To summarize my problem, the below query in my view only works when the post comes from the submit button and not when it comes from my dropdownlist.
#{var rates= Model.Rates.Where(a => a.PanelID == ViewBag.PanelID).OrderBy(a => a.minCount).ToList();}
How does it look in the rendered page? You may have two elements being rendered with the same name/id:
#Html.DropDownList("PanelID", (SelectList)ViewData["PanelDropDown"], new { onchange = "$('#RateForm').submit()"
and
#Html.HiddenFor(modelItem => rates[i].PanelID)
I suggest you use Firefox/Firebug to examine the actual request that it is being made. I can't imagine that the form will post differently if triggered via the submit vs. the button, but I suppose it's possible.
On a larger note, I would make a couple of comments about your design.
I would use ViewBag properties for your selections rather than key-based access to ViewData. This will be much more readable in both your controller and your view.
Consider having a separate action that populates the information filtered by the dropdown list. Render that action in your view based on the PanelID and call that action via AJAX to get the new HTML rather than doing a full form post.
Avoid applying your handlers in your markup. Rather, add an optional Scripts section to your master page and, when needed, add scripts to your page that apply your behaviors through that section. This allows you to control via the master where view-specific scripts are placed in the document and keeps your behaviors separate from your document structure, a best practice for readability.
I found the problem. It looks like because I was only looping through a subset of my navigation property (Rates filtered by panelID), the model that was returned from the view only had that subset of navigation properties available to it. After saving the changes, I just redefined my model (called the record from the database again) and it looks good now.
Ie. There were supposed to be 140 records in my navigation property, filtering by panelID == 1 narrowed it down to 28 records. For some reason the entity framework decided that it didn't feel like maintaining the relationship to the other 112 records, so when I changed the dropdown to filter by panelID == 2, the only records available all had panelID == 1 and returned null.

ASP.NET MVC DropDownListFor does not honour SelectListItem.Selected

I am using DropDownListFor to render a dropdown list in a view. Somehow the rendered list does not select the SelectListItem with Selected set to true.
In the controller action:
var selectList = sortedEntries.Select(entry => new SelectListItem
{
Selected = entry.Value.Equals(selectedValue),
Text = entry.Value,
Value = entry.Id
});
return View(new DropDownListModel
{
ListId = id,
SelectList = selectList,
OptionLabel = "Click to Select"
});
In the view:
<%= Html.DropDownListFor(m => m.ListId,
Model.SelectList,
Model.OptionLabel,
new {#class="someClass"}) %>
I have tried the following:
make sure that there is one and only one items with Selected set to true.
remove the option label argument.
remove the HTML attribute object.
use SelectList in DropDownListFor:
Html.DropDownListFor(m => m.ListId,
new SelectList(Model.SelectList, "Value", "Text",
new List<SelectListItem>(Model.SelectList).Find(s => s.Selected)),
new {#class="someClass"})
Any suggestions as to what went wrong?
EDIT:
more information:
This action is a child action, called by another view with HTML.RenderAction
DropDownListFor will always select the value that the listbox is for, so in this case it will look at the value of ListId and make that item in the list selected. If ListId is not found in the list, the first item (or default text) will be selected. If you want a list that selects based on the selected attribute use DropDownList (without the For, in that case you have to name it yourself).
So in your case this would work:
var selectList = sortedEntries.Select(entry => new SelectListItem
{
Text = entry.Value,
Value = entry.Id
});
return View(new DropDownListModel
{
ListId = selectedValue,
SelectList = selectList,
OptionLabel = "Click to Select"
});
I got the same problem on the same model (with the other models in the decision no problem)
Does not work:
#Html.DropDownListFor(o => o.Drivers.ValueListItems.Value, Model.Drivers.ValueListItems, new { size = Model.Drivers.ValueSizeList, Multiple = "multiple" })
Works perfectly, the elements selected:
#Html.DropDownListFor(o => o.Drivers.ValueListItems.ToDictionary(u=>u.Value).Values, Model.Drivers.ValueListItems, new { size = Model.Drivers.ValueSizeList, Multiple = "multiple" })
Try like this:
var selectList = sortedEntries.Select(entry => new SelectListItem
{
Text = entry.Value,
Value = entry.Id
});
return View(new DropDownListModel
{
// The drop down list is bound to ListId so simply set its value
// to some element value in the list and it will get automatically
// preselected
ListId = selectedValue,
SelectList = selectList,
OptionLabel = "Click to Select"
});
and in the view:
<%= Html.DropDownListFor(
m => m.ListId,
new SelectList(Model.SelectList, "Value", "Text"),
Model.OptionLabel,
new { #class = "someClass" }
) %>
There could be one more gotcha: you are trying to change the selected value in a POST action. For example you rendered a form, the user selected some value in the dropdown, submitted the form and in your POST action you do some processing on this selected value and when you redisplay the view you want the drop down list to have some other value selected. In this case you will have to remove the initial selection which is contained in the ModelState or the Html helper will ignore the selected value in the model:
// do this before returning the view and only if your scenario
// corresponds to what I described above
ModelState.Remove("ListId");
The solution for this problem is simpler that we all think...
All we need to do is set the property on the view model for the element that the dropdown is bound to - i.e: ListId = 3 for example
this way when we do this
Html.DropDownListFor(m => m.ListId,
new SelectList(Model.SelectList, "Value", "Text",
new List<SelectListItem>(Model.SelectList).Find(s => s.Selected)),
new {#class="someClass"})
the HtmlHelper will automatically pick up the default value to display on the DropDownList
simples!
Hope it may help you and all the others - like me! - that have lost a lot of time searching for a solution for this apparent issue.

DropDownListFor Not Selecting Value

I'm using the DropDownListFor helper method inside of an edit page and I'm not having any luck getting it to select the value that I specify. I noticed a similar question on Stackoverflow. The suggested workaround was to, "populate your SelectList in the view code". The problem is that I've already tried this and it's still not working.
<%= Html.DropDownListFor(model => model.States, new SelectList(Model.States.OrderBy(s => s.StateAbbr), "StateAbbr", "StateName", Model.AddressStateAbbr), "-- Select State --")%>
I have set a breakpoint and have verified the existence (and validity) of model.AddressStateAbbr. I'm just not sure what I'm missing.
After researching for an hour, I found the problem that is causing the selected to not get set to DropDownListFor. The reason is you are using ViewBag's name the same as the model's property.
Example
public class employee_insignia
{
public int id{get;set;}
public string name{get;set;}
public int insignia{get;set;}//This property will store insignia id
}
// If your ViewBag's name same as your property name
ViewBag.Insignia = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);
View
#Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.Insignia, "Please select value")
The selected option will not set to dropdownlist, BUT When you change ViewBag's name to different name the selected option will show correct.
Example
ViewBag.InsigniaList = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);
View
#Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.InsigniaList , "Please select value")
If you're doing it properly and using a model--unlike all these ViewBag weirdos--and still seeing the issue, it's because #Html.DropDownListFor(m => m.MyValue, #Model.MyOptions) can't match MyValue with the choices it has in MyOptions. The two potential reasons for that are:
MyValue is null. You haven't set it in your ViewModel. Making one of MyOptions have a Selected=true won't solve this.
More subtly, the type of MyValue is different than the types in MyOptions. So like, if MyValue is (int) 1, but your MyOptions are a list of padded strings {"01", "02", "03", ...}, it's obviously not going to select anything.
Try:
<%= Html.DropDownListFor(
model => model.AddressStateAbbr,
new SelectList(
Model.States.OrderBy(s => s.StateAbbr),
"StateAbbr",
"StateName",
Model.AddressStateAbbr), "-- Select State --")%>
or in Razor syntax:
#Html.DropDownListFor(
model => model.AddressStateAbbr,
new SelectList(
Model.States.OrderBy(s => s.StateAbbr),
"StateAbbr",
"StateName",
Model.AddressStateAbbr), "-- Select State --")
The expression based helpers don't seem to respect the Selected property of the SelectListItems in your SelectList.
While not addressing this question - it may help future googlers if they followed my thought path:
I wanted a multiple select and this attribute hack on DropDownListFor wasn't auto selecting
Html.DropDownListFor(m => m.TrainingLevelSelected, Model.TrainingLevelSelectListItems, new {multiple= "multiple" })
instead I should have been using ListBoxFor which made everything work
Html.ListBoxFor(m => m.TrainingLevelSelected, Model.TrainingLevelSelectListItems)
I also having similar issue and I solve it by as follows,
set the
model.States property on your controller to what you need to be selected
model.States="California"
and then you will get "California" as default value.
I encountered this issue recently. It drove me mad for about an hour.
In my case, I wasn't using a ViewBag variable with the same name as the model property.
After tracing source control changes, the issue turned out to be that my action had an argument with the same name as the model property:
public ActionResult SomeAction(string someName)
{
var model = new SomeModel();
model.SomeNames = GetSomeList();
//Notice how the model property name matches the action name
model.someName = someName;
}
In the view:
#Html.DropDownListFor(model => model.someName, Model.SomeNames)
I simply changed the action's argument to some other name and it started working again:
public ActionResult SomeAction(string someOtherName)
{
//....
}
I suppose one could also change the model's property name but in my case, the argument name is meaningless so...
Hopefully this answer saves someone else the trouble.
I know this is an old question but I have been having the same issue in 2020.
It turns out the issue was with the model property being called "Title", I renamed it to "GivenTitle" and it now works as expected.
From
Html.DropDownListFor(m => m.Title, Model.Titles, "Please Select", new { #class = "form-control" })
to
Html.DropDownListFor(m => m.GivenTitle, Model.GivenTitles, "Please Select", new { #class = "form-control" })
this problem is common. change viewbag property name to other then model variable name used on page.
One other thing to check if it's not all your own code, is to make sure there's not a javascript function changing the value on page load. After hours of banging my head against a wall reading through all these solutions, I discovered this is what was happening with me.
The issue at least for me was tied to the IEnumerable<T>.
Basically what happened was that the view and the model did not have the same reference for the same property.
If you do this
IEnumerable<CoolName> CoolNames {get;set;} = GetData().Select(x => new CoolName{...});}
Then bind this using the
#Html.DropDownListFor(model => model.Id, Model.CoolNames)
The View loses track of the CoolNames property,
a simple fix is just to add .ToList() After dooing a projection (.Select()) ;).
I had the same problem. In the example below The variable ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] has a SelectListItem list with a default selected value but such attribute is not reflected visually.
// data
var p_estadoAcreditacion = "NO";
var estadoAcreditacion = new List<SelectListItem>();
estadoAcreditacion.Add(new SelectListItem { Text = "(SELECCIONE)" , Value = " " });
estadoAcreditacion.Add(new SelectListItem { Text = "SI" , Value = "SI" });
estadoAcreditacion.Add(new SelectListItem { Text = "NO" , Value = "NO" });
if (!string.IsNullOrEmpty(p_estadoAcreditacion))
{
estadoAcreditacion.First(x => x.Value == p_estadoAcreditacion.Trim()).Selected = true;
}
ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] = estadoAcreditacion;
I solved it by making the first argument of DropdownList, different to the id attribute.
// error:
#Html.DropDownList("SELECT__ACREDITO_MODELO_INTEGRADO"
, ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] as List<SelectListItem>
, new
{
id = "SELECT__ACREDITO_MODELO_INTEGRADO"
...
// solved :
#Html.DropDownList("DROPDOWNLIST_ACREDITO_MODELO_INTEGRADO"
, ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] as List<SelectListItem>
, new
{
id = "SELECT__ACREDITO_MODELO_INTEGRADO"
...

Resources