ASP.NET MVC - How to get checkbox values on post - asp.net-mvc

Hey all, this is a newbie ASP.NET MVC question.
I have a view that has a list of checkboxes and a submit button. On submit it posts to a controller method but I can't figure out how to get the values of the checkboxes. Also, I can't figure out how to get model data that I passed into the view when I'm in the post method, I tried using Html.Hidden but that didn't seem to work.
Here's the code:
http://pastebin.com/m2efe8a94 (View)
http://pastebin.com/m39ebc6b9 (Controller)
Thanks for any input received,
Justin

First thing I noticed is that your hidden fields need to be inside your form. Currently in your view, they are above the BeginForm, so they won't be included in the form submission.
To get the values of the selected check boxes, add an IsOffered parameter to your OfferTrade Action method.
public ActionResult OfferTrade(FormCollection result, List<string> IsOffered)
That parameter will contain a list of the ItemId's for all the checked IsOffered boxes.
The HtmlHelper's CheckBox works differently and I don't like the way it works, so I don't use it.
Making the IsOffered parameter type List<int> should also work if your ItemId field is an integer.

First of all your ItemId and UserId is outside your form:
<%= Html.Hidden("ItemId", Model.ItemIWant.ItemId) %>
<%= Html.Hidden("UserId", Model.ItemIWant.UserId) %>
//...
<% using (Html.BeginForm()) {%>
Secondly you could try to make your Controller action method use "model binding" (if this is also called model binding)
public ActionResult OfferTrade(int ItemId, int UserId, IList<string> IsOfferred)
Edit Just noticed you are not using the HtmlHelper CheckBox so your list will contain only selected items, but a point still:
You might want to look into Phil Haacks post on Model Binding To A List, but there is a small change to this in the RTM version of MVC:
You dont need the ".Index" hidden fields, but then the indexes in the Name fields must be zero-indexed and increasing (by 1).

Related

How to retrieve both Text and Value from DropDownList in Asp.net mvc

I have a dropdownlist in asp.net mvc which is bound using the normal binding syntax
and I can retrieve the "value" in the controller.
But I also need to display the text that is associated with this value.
I can go the hard route and query the db for this associated value.
But I wanted to know if there is an easy way to retrieve the Text as well as the Value in the controller.
Sample code I used
<%= Html.DropDownList("State","Pick a State")%>
which displays
"NJ", "New Jersey" etc.
In Controller
public ActionResult SelectState(string State)
{
// I have value of State (NJ) ...I also need the Text for this
}
Any help would be appreciated.
Thanks
The value that will come as part of the form submission is the value of the dropdown item. To get both, you could change the value to be something like "value delimiter text", so something like "NJ|New Jersey". Then you could parse it in the controller.

getting dropdown's text in Post action method

I have a Razor view in my asp.net MVC3 application with a dropdownlist like this:
#Html.DropDownListFor(model => model.Account.AccountType, new SelectList(Model.AccountTypes, "AccountTypeCode", "Abbreviation"))
This dropdown is inside a form. When form is posted to action method and viewmodel is filled because of model binding, It get the value(AccountTypeCode) and not the text "Abbreviation" property of dropdownlist. I want to get both of these. how can I get these in post action method.
Please suggest.
If you need more than one property of an object as a value for a dropdown, the easiest way is to create a combination of these in a partial class
EF 4, how to add partial classes this quesion should help you. You will be able to combine values under one property that you will provide to your dropdown helper.
If you don't want to use partial classes I would advise creating your own helper, that will be a lot easier than trying to use something that does not fit your needs. You can do something like :
#helper CustomDropdown(string name, IEnumerable<AccountTypes> valueList)
{
<select>
#foreach (var item in valueList)
{
<option value="#item.Abbreviation #AccountTypeCode">#item.Abbreviation</option>
}
</select>
}
Google "Creating an Inline HTML Helper" to get some valuable resources on that topic
I struggled with this recently, and the best I could do was:
ViewBag.Message = myModel.myProperty.ToString().
in the controller action. Assuming myProperty is AccountType.
Then in my view I just did
#ViewBag.Message
The next problem I encountered is that it spit out the exact text, without spacing. I had to use a helper to add spacing (but it was based on each word being capitalized, so "ThisIsSomeText" would show up as "This Is Some Text".

Confused by How ASP .NET MVC Populates Fields Based on View Model and Posted Form Values

Not sure if this question has already been asked.
I am developing an ASP .NET MVC 2 site. My view has a drop down where user can select which record to display for editing. When this drop down is changed, the field values for the currently selected record automatically get posted to the server and are saved in the session. In the response the server then returns a view for editing the newly selected record.
The problem I am having is that some of the field values from the previous record are being remembered when the new record is displayed.
In my view I have something like the following which is causing the problem:
<%= Html.TextBox("ActionTypeDetails.DisplayName",
Model.ActionTypeDetails.DisplayName) %>
Here I want the posted data to populate a parameter called ActionTypeDetails which has multiple properties including DisplayName.
My controller actions looks something like this:
public ActionResult EditActionType(Guid PluginEditID,
Guid? SelectedActionTypeID,
ActionTypeViewObj ActionTypeDetails)
I have tried changing my view to this:
<%= Html.TextBox("PostedActionTypeDetails.DisplayName",
Model.ActionTypeDetails.DisplayName) %>
And my controller action to this:
public ActionResult EditActionType(Guid PluginEditID,
Guid? SelectedActionTypeID,
ActionTypeViewObj PostedActionTypeDetails)
Yet it still exhibits the same problem. Can someone please explain the logic to why it works like this? What is the easiest workaround that would still allow me to use the built in model binding? I know I can clear the ModelState but this is not ideal as I want some of the other data on the form to be remembered.
If you post back to the same url, asp.net has mechanisms which preserve field values. More info can be found here.

.net MVC RenderPartial renders information that is not in the model

I have a usercontrol that is rendering a list of items. Each row contains a unique id in a hidden field, a text and a delete button. When clicking on the delete button I use jquery ajax to call the controller method DeleteCA (seen below). DeleteCA returns a new list of items that replaces the old list.
[HttpPost]
public PartialViewResult DeleteCA(CAsViewModel CAs, Guid CAIdToDelete)
{
int indexToRemove = CAs.CAList.IndexOf(CAs.CAList.Single(m => m.Id == CAIdToDelete));
CAs.CAList.RemoveAt(indexToRemove);
return PartialView("EditorTemplates/CAs", CAs);
}
I have checked that DeleteCA is really removing the correct item. The modified list of CAs passed to PartialView no longer contains the deleted item.
Something weird happens when the partial view is rendered. The number of items in the list is reduced but it is always the last element that is removed from the list. The rendered items does not correspond to the items in the list/model sent to PartialView.
In the usercontrol file (ascx) I'm using both Model.CAList and lambda expression m => m.CAList.
How is it possible for the usercontrol to render stuff that is not in the model sent to PartialView?
Thanx
Andreas
It sounds like the ModelState is the trouble here, as you bind to CAs the ModelState save this values in the background as Attempted Values, so its true the object is no longer present at the Model, but the ModelSate still have the values of the deleted object. You can try a:
ModelState.Clear();
To remove all those old values.
Check in firebug what the response realy is. This way you can see if you have a serverside problem or it is a jquery issue.

Form Submits same checkbox values on subsequent submit action in MVC

I have followed the suggestion in this question...
[How to handle checkboxes in ASP.NET MVC forms?
...to setup multiple checkboxes with the same name="..." attribute and the form behaves as expected the FIRST time its submitted. Subsequent submissions of the form use the original array of Guid values instead of properly sending the new array of checked item values.
Relevant code in the view...
<% foreach (ItemType itemType in ViewData.Model.ItemTypes) %>
<%{ %>
<li>
<input id="selectedItems" name="selectedItems" type="checkbox" value="<%= itemType.Id%>" />
<%= itemType.Description %></li>
<%} %>
This produces a series of checkboxes, one each for each item with the value="..." attribute set to the Id of the item.
Then in my controller action, the method signature is...
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SelectItems(Guid[] selectedItems)
{...}
The first time thru the method, the selectedItems array properly holds the Guid of each item selected. But subsequent submits of the form will always still contain whatever was first selected in the initial submit action, no matter what changes you make to what it checked before you submit the form. This doesn't seem to have anything to do with my code, as inspecting the selectedItems array that the MVC framework passes to the method evidences that the framework seems to always be submitting the same value over and over again.
Close browser, start again, selecet different initial checkbox on submit and the process starts all over again (the initially-selected checkbox ids are always what's in the selectedItems argument).
Assume I must be thick and overlooking some kind of caching of form values by the framework, but I would swear this didn't behave this way in Preview 5.
Driving me nuts and probably simple issue; any ideas????
FWIW, here is what I do (not sure if it related):
// please MS, stop screwing around!!!!!!!!!!!!!!!
string r = Request.Form["r"];
Then proceed to extract the values manually from 'r'. I still use Preview 4, as they have really broken too many existing features, and not fixed reported bugs.
I'm not sure what is causing your issue, but I have a WAG...
Do you RedirectToAction in your controller's Post method?
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SelectItems(Guid[] selectedItems)
{
/* lol snip */
return RedirectToAction("WhateverActionIsTheGetVersionOfThisPostAction");
}
It might serve to reset anything going on in the background... Again, wild-ass guess...

Resources