MVC3 get Select Box Option Name as Well as Value - asp.net-mvc-3

<select id="selectedSchool" size="3" multiple="multiple" name="selectedSchool">
#foreach (var item in ViewBag.pt)
{
<OPTION VALUE="#item.entityID">#item.name</OPTION>
}
</select>
on my page the user selects a school from the list of schools, each school has a unique ID which is needed and passed via the VALUE attribute, I also would like to pick up the name
(item.name) that was selected how can I resolve this info from my control Action Result?
public ActionResult ResultsSchoolsAttended(List<int> selectedSchool)
i iterate through the list of results, but I would aslo like selectedSchool.name to enter back in the db as 'display text'
how can i do this?

Well, MVC can only give you what is in the HTTP POST. And if you look at that, you will see that the <option> inner HTML isn't there. So you have only two choices:
Include it in the value in your markup, or
Look it up in your ResultsSchoolsAttended action based on the submitted value.
I'd pick the second, personally.

Related

Laravel Livewire Autofill Input Box Based On Drop Down Selection

I am asking for help. Is there any way I could fill an input box based on drop down selection? On my modal I have a dropdown option for subject description and I would like the subject number input field dynamically change its value. Any help would be much appreciated.
This is how I retrieved the data for my dropdown
subjects=DB::table('programs_subj')->select('corsdes', 'corsno')->get()
This is my dropdown code for the subject description which is working and the selected is saved but I could quite how to incorporate the subject number
<select name="corsdes" id="corsdes" wire:model="corsdes">
<option value="corsdes" wire:model="corsdes"></option>
#foreach($subjects as $sbj)
<option value="{{ $sbj->corsdes }}">{{ $sbj->corsdes}}</option>
#endforeach
</select>
<input name="corsno" id="corsno" wire:model="corsno"><input>
if you have the public properties $corsdes and $corsno then:
public function updatedCorsdes($value)
{
$this->corsno = $this->subjects->where('corsdes',$value)->first()->corsno;
}

MVC matching ModelState keys to ViewModel collection

Is it possible to match a ViewModel property to the matching ModelState.Key value when the ViewModel is a (has a) collection?
Example: To edit a collection of viewmodel items, I am using the extension found here.
That adds a GUID to the id of the fields on the page.
example:
class Pets
{
string animal;
string name;
}
For a list of Pets, the generated html source is like this:
<input name="Pets.index" autocomplete="off" value="3905b306-a9..." type="hidden">
<input value="CAT" id="Pets_3905b306-a9...__animal" name="Pets[3905b306-a9...].animal" type="hidden">
<input value="MR. PEPPERS" id="Pets_3905b306-a9...__name" name="Pets[3905b306-a9...].name" type="hidden">
<input name="Pets.index" autocomplete="off" value="23342306-b4..." type="hidden">
<input value="DOG" id="Pets_23342306-b4...__animal" name="Pets[23342306-b4...].animal" type="hidden">
<input value="BRUTICUS" id="Pets_23342306-b4...__name" name="Pets[23342306-b4...].name" type="hidden">
So when this gets bound on post, the ModelState gets loaded with all the form fields.
In ModelSTate.Keys, there is:
Pets[23342306-b4...].name
Pets[23342306-b4...].animal
Pets[3905b306-a9...].name
Pets[3905b306-a9...].animal
Everything good so far, but I am doing some business logic validation, things like, cant add new animal if one exists with the same name. In that case, I want to be able to highlight the input field that is in error.
So if my create function fails, it will return an error/key value pair like this:
{ error = "Duplicate Name", key="name" }
So I at least will now what property caused the problem.
But since my repository functions don't know about the view field ids, how can I match the key "name" to the appropriate ModelState key (in this case, either Pets[23342306-b4...].name or Pets[3905b306-a9...].name)?
If you used the built in functionality of MVC for displaying collections (Html.DisplayFor(m => m.Pets) or Html.EditorFor(m => m.Pets)) with appropriate display/editor template, MVC would render something like this:
Pets[0].name
Pets[0].animal
Pets[1].name
Pets[1].animal
This maps to IEnumerable<Pets> and you know that first item has index of 0, second item 1 etc.
So if the second item has an error, you can set error for the ModelState key "Pets[1].name" for example.
If you are using the Html.BeginCollectionItem extension method, like I was, I was able to get around this by not using the GUID. I need the dynamic add and delete, but I was always looking up known items, persons that have an ID, which I had in my editor. So instead of using the GUID, I just assign the ID (uniqueId) in the code below. I could then find the key because I knew it was Person[234232]. Of course if you are adding new items and not displaying selected items, it might not work for you.
public static IDisposable BeginCollectionItem(this HtmlHelper html, string collectionName, string uniqueId)
{
var idsToReuse = GetIdsToReuse(html.ViewContext.HttpContext, collectionName);
string itemIndex = idsToReuse.Count > 0 ? idsToReuse.Dequeue() : uniqueId;
// autocomplete="off" is needed to work around a very annoying Chrome behaviour whereby it reuses old values after the user clicks "Back", which causes the xyz.index and xyz[...] values to get out of sync.
html.ViewContext.Writer.WriteLine(string.Format("<input type=\"hidden\" name=\"{0}.index\" autocomplete=\"off\" value=\"{1}\" />", collectionName, html.Encode(itemIndex)));
return BeginHtmlFieldPrefixScope(html, string.Format("{0}[{1}]", collectionName, itemIndex));
}

Posting an array of Guid pairs to an Action

As you can see here, I'm allowing a user to dynamically create a table of data, and storing the ids of the table in a hidden field (in the example it's a text area so you can see it, and the final solution will be Guid rather than integers).
My question is simply this: What data type should I use on the server/MVC action to take the data held in the textarea/hidden field?
At the moment I have a string, and am contemplating doing a load of .split()'ing and whatnot, but it doesn't feel right!
Ultimately I need some sort of IEnumerable<Guid, Guid> thing?!?! so I can do a foreach and get each pair of Ids.
I'm sure the answer will be simple, but I can't think of what to do.
Any help appreciated.
If your UI has multiple, like-named form fields, they will be submitted to your action method and bound properly to an array. We could use string[] for this case.
<form action="">
<input type="text" name="guids"/>
<input type="text" name="guids"/>
<input type="text" name="guids"/>
<input type="text" name="guids"/>
<input type="submit" value="Submit"/>
</form>
Then your controller could handle them like so:
public ActionResult MyAction(string[] guids)
{
guids.Count == 4 // if all four fields were filled in.
}
Note that if there is just a single guids value sent by the form, the string[] guids will still work - it will contain just a single item.
Finally, note that if no values are entered, the array value will be null, not an empty array.
You can actually bind to a list from your model, take a look at this post
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

MVC3 Listbox Contents to Model Values

I'm using ASP.NET MVC3 and I was wondering if there's any way to create a listbox that contains the values which I would like my model to have.
Using #Html.ListBoxFor will only store the selected items into the model when the form is submitted rather than all the items in the listbox. I plan on using javascript to add items from another textbox.
Thanks
You are not clear, but are you trying to POST values back? If so, then they must be selected (i.e. active) form values in order to POST. If you use JavaScript to add options to a listbox (HTML select> then these don't post. You would need a multi-select enabled select and then flag each value you want to submit as selected.
To get values back they need to POST in some manner.
No. This has nothing to do with MVC3. This is a limitation of the HTTP model. When a form is posted, the browser only posts the selected value. It does not post the other elements of the select list.
MVC must work within the framework of the way the browsers work, and this can't be changed.
Yes, you can do this. You need a couple things to make this work though, it can be troubling.
In view:
//generate list box with
<select id="NAMEOFLISTBOX" name="NAMEOFLISTBOX" multiple="multiple">
Okay, here is the part that most people miss. The controller will only collect selected items if they are actually designated to be selected. Therefore, where your submit button is you need to include some javascript.
<input type="submit" value="DO WORK" onclick="selectLISTBOXITEMS()" />
Script:
function selectLISTBOXITEMS(){
var curList = document.getElementById("NAMEOFLISTBOX");
for (var i = 0; i < curList.length; i++) {
curList.options[i].selected = true;
}
}
In controller:
[HttpPost]
public ActionResult controllerName(List<string> NAMEOFLISTBOX)
{
foreach(string s in NAMEOFLISTBOX)
{
//do work
}
return RedirectToAction("controllerGet");
}
Not impossible, but the first time I did this it took a while to figure out why nothing was being sent.

asp.net helper for DropDownList won't render correctly

I'm attempting to get a dropdown list to select the correct value when the page loads.
#Html.DropDownList("CounterpartyTypeSelect", new SelectList(ViewBag.CounterpartyTypeOptions, "DefaultId", "Value"), new { #class = "selectbox", selected = Model.CounterpartyType })
However, when the page renders it always selects the first value in the dropdown list.
The html source for the page:
<select class="selectbox" id="CounterpartyTypeSelect" name="CounterpartyTypeSelect" selected="977980f2-ebb2-4c2a-92c2-4ecdc89b248d">
<option value="5802239e-c601-4f1e-9067-26321213f6e6">Societa per Azioni (SpA)</option>
<option value="f8160341-4a69-436f-9882-4da31a78f1d5">Gesellschaft mit beshrankter Haftung (GmbH)</option>
<option value="977980f2-ebb2-4c2a-92c2-4ecdc89b248d">Sociedad Anonima (SA)</option>
<option value="cdbeb1d3-301b-4884-b65a-612ddd8306f3">Private Limited Company (Ltd)</option>
<option value="1fe68d96-f31b-4859-9869-8c76a5eb1508">Corporation (Inc)</option>
<option value="9c9e5722-ab59-4d1c-a0a3-91b42a3ee721">Limitada (LTDA)</option>
<option value="0cb57339-8705-4e3a-8f6a-95e9664962b7">Public Limited Company (Plc)</option>
<option value="0924d6f1-06a9-49a3-ac05-b3e2686a0e92">Partnership</option>
<option value="c8fbe021-a8f7-4e9d-ab38-dbeb5af5a631">Limited Liability Company (LLC)</option>
<option value="30d9e22b-34f5-43c5-8471-e614dbedb6a6">Aktiengesellschaft(AG)</option>
</select>
As you can see it is putting the "selected" attribute into the outer select tag instead of on the option that matches the Id. I have another select with identical parameters (except variable names of course) and it renders correctly this way. I do not want to use DropDownListFor<T> because I have a HiddenFor field that actually submits this value in the form and javascript that sets the value to match the Select choice. I've confirmed my database is storing the values that I set correctly. What is going on?
SelectList() has an overload for you to choose the selected item. You are adding it as an HTML attribute in the helper and those get rendered to the parent select tag.
Do this:
#Html.DropDownList("CounterpartyTypeSelect", new SelectList(ViewBag.CounterpartyTypeOptions, "DefaultId", "Value", Model.CounterpartyType), new { #class = "selectbox" })
Use the overload for SelectList that takes four arguments:
new SelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue);
What's happening in the first line of your code new { #class = "selectbox", selected = Model.CounterpartyType } is you're providing the selected attribute as an HTML attribute of the parent select element.
So you see selected="977980f2-ebb2-4c2a-92c2-4ecdc89b248d" appearing in your first line of output, which btw doesn't do anything.
Also you're providing the value to search for in the Helper as a hardcoded string "value" instead of the actual value you need from the model. The browser will default to the first option since it can't find any value matching 'value'.
To fix this, provide Model.CounterpartyType as the third parameter to your SelectList parameter instead of 'value'.

Resources