How to get DropDownList selected Text in MVC controller - c#

I have this DropDownList in html where i can select the Texts.Text = Project, Value = ID
#Html.DropDownList("Project", new SelectList(Model.dropConfig, "Project", "ID"), "-- Select LineID --", new { required = true, #class = "form-control" })
On click submit button in the controller I can see that the Value (ID) is passed on to be posted back to DB. I want the Text to be post into DB.
Controller side code line:
detailsConfig.Project = Convert.ToString(form["Project"]);
For example:
If the dropdownlist values are
Project ID
test 1
testagain 2
In controller I should get test, not 1. Please help

You use that drop-down change event and store that name in hidden filed and get that value to controller.
View:-
#Html.DropDownList("Project", new SelectList(Model.dropConfig, "Project", "ID"), "-- Select LineID --", new { required = true, #class = "form-control",#id="ddlProject" })
<input type="hidden" id = "hdnProjectName" name="ProjectName" />
Jquery:-
$("#ddlProject").on("change", function () {
$("#hdnProjectName").val($(this).find("option:selected").text());
});
Controller:-
public ActionResult Save(FormCollection formcollection)
{
var projectName = formcollection["ProjectName"];
}

new SelectList(Model.dropConfig, "Project", "Project")
The above change solves my problem. Thanks #StephenMuecke :)

First, you should definitely strongly-type your dropdownlist to your model.
What I mean is this...
In the controller is where I would create the selectlist to be used in the view.
Controller
ViewBag.ProjectSelection = new SelectList(/* your data source */, "Project", "Project");
Disclaimer:
Submitting the Text value is not preferred because typically the Text value of the select element is not unique. Submitting the ID to the server is the best practice.. and then you can simply query the database based on the ID you submitted to get the values you want. This is the best way to get the most accurate and reliable data.
Then in your view, strongly-type your ProjectSelection selectlist to the Project property in your model.
View
#Html.DropDownListFor(model => model.Project, (IEnumerable<SelectListItem>)ViewBag.ProjectSelection, "-- Select LineID --", new { required = true, #class = "form-control" })
Why are you declaring required in the dropdownlist? That should be declared in your model.
Explanation
In MVC, when it comes to HTML elements where the user can select options to be submitted to the server (dropdownlist, listbox, etc).. only the Value will be submitted (which in your case was the ID). The Text portion of the element is just for the user to see to make their selection's easier.
Let me know if this helps!

Related

.NET Display different database variable but save as ID?

I don't know how to sum up what I'm trying to do in the title properly! Basically I have created a controller with EF6 and one foreign key of the Client table is MJTopicsID which links to the MJTopics table, a table of 26 topics. In the add and edit view I want the MJTopicsID to be a drop down menu displaying all the topics available however when you select it and click to add or edit an entry it adds it to the Client table as the MJTopicsID foreign key number? How do I go about this so I can apply it to all of my views.
This is the dropdown menu I created in the edit view however it just shows numbers 1-26 and if I change it to the topics variable it doesn't know it as obviously its not in the open model, thanks!
<div class="form-group">
#Html.LabelFor(model => model.MJTopicsID, "MJTopicsID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("MJTopicsID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.MJTopicsID, "", new { #class = "text-danger" })
</div>
</div>
If I understood correctly then you want to display some readable value and save some db specific value like foreign key Id in this case.
In the view for helper method "DropDownList" you can give second parameter of type IEnumerable type as a list of your options like this:
View:
#Html.DropDownList("MJTopicsID",
(List<SelectListItem>)#ViewBag.MJTopics,
htmlAttributes: new { #class = "form-control" })
Action:
public ActionResult Index()
{
ViewBag.MJTopics = new List<SelectListItem>() {
new SelectListItem(){Text = "Topic1", Value ="1" },
new SelectListItem(){Text = "Topic2", Value ="2" }
};
return View();
}
SelectListItem has two properties which you can map with your models.
Also you can use your model with "Text" as value to display and "value" as value to use.
Let "topics" is your list model for topics
then you can write it as
topics.Select(
x=> new SelectListItem()
{
Text = x.Id,
value =x.Desc
})
This is the one way of doing it.
I hope it will solve your problem.
I wanted to add an answer if anyone is new to EF6 and is trying to do the same thing.
In the controller for the actionresult you are trying to do this for, so in my case create it will create a viewbag variable this was mine:
ViewBag.MJTopicsID = new SelectList(db.MJTopicss, "ID", "ID");
I changed it to:
ViewBag.MJTopicsID = new SelectList(db.MJTopicss, "ID", "topicalTF");
The topicalTF is the variable for the topics available and this showed all the topics but would save it as the ID, hope this helps!

add extra option to an already populated dropdownlist in mvc

I have an html dropdownlistfor which is being populated from my database, this I was able to do successfully but the issue I am having now is including an additional option not available in the database as an option that can also be selected.it is actually a list of items but I want a give an option ALL which when selected means the user is selecting all the items displayed in the database, my major issue is how to include the ALL option. I have searched and read similar questions but they are not what am trying to achieve. thanks for your help. here is my code
in my controller I have this:
var load = from bh in db.IV_001_ITEM
select bh;
ViewBag.selection = new SelectList(load.ToList(), "item_code", "item_name", glay.vwstring2);
in my view I have this:
<div class="col-sm-2">
#Html.DropDownListFor(m => m.vwstring2, ViewBag.selection as SelectList, "Select", new { #class = "form-control", required = "required", id = "selectc" } )
</div>
You can use the Add method to explicitly add an extra option (SelectListItem)
List<SelectListItem> optionList = db.IV_001_ITEM
.Select(x=>new SelectListItem { Value=x.item.code,
Text=x.itemName}).ToList();
// Now add the item you want
optionList.Add(new SelectListItem { Value="Foo",Text="Bar"});
//use this now
ViewBag.Items = optionList;
// You can set the selected item on your view model property
myViewModelObject.vwstring2 = glay.vwstring2; //For the selected item
return View(myViewModelObject);
In your view,
#Html.DropDownListFor(m => m.vwstring2, ViewBag.Items as List<SelectListItem>,
"Select", new { #class = "form-control"})

DropDownListFor How to set a default value from a database

So, I got a DropdownListfor that looks like that in my view:
#Html.DropDownListFor(m => m.ProductCategory, new SelectList(Model.ProductCategories.OrderBy(m => m.PCNumber), "", "Name"), "")
That works like it should. In my next view the user should be able to edit his order. So what I want to do is, if he opens the form all of his data from before should be displayed, for textboxes I got it work with the following code:
#Html.TextBoxFor(m => m.NameOfProduct, new { #Value = #Model.NameofProduct })
So now my problem is how can I do the same thing that I did with my textboxes (giving them default values from my model) for a DropDownListFor when the value is stored in my model(database)? It should like that if he selected Category 3 before and now wants to edit his order from before, the dropdownlist should show category 3 right away.
Thank you for any help!
Try this code may be it work in your situation.
#Html.DropDownListFor(m=> m.PCNumber, new SelectList(m.ProductCategories, "PCNumber", "ProductCategory"), "-- Select Category --", new { #class = "form-control" })
here you will get default edit order in your dropdown
[HttpGet]
public ActionResult EditOrder(int? id)
{
_obj_order_detail = db.order_detail.Find(id);
if (_obj_order_detail != null)
{
_obj_order_detail.ProductCategories = db.category_detail.ToList(); //get category List
return View(_obj_order_detail);
}
else
{
return view();
}
}
this will return view with order which you want to edit and ProductCategories and dropdown bu default contain ProductCategory which you want to edit

Getting the chosen item from DropDownList

I use JavaScript for populating a list called "groups".
Then I create a DropDownList:
<div class="form-group">
<div class="col-md-10">
#Html.DropDownList("groups", new SelectList(string.Empty, "Value", "Text"), "Choose...")
</div>
</div>
The DropDownList displays fine.
What I need to do is assign the chosen value from "groups" to the model.group_id.
I don't know how to get the item chosen in DropDownList in the controller method. Thank you for any advice.
If you need it to bind to group_id then use that as the name:
#Html.DropDownList("group_id", ...)
Or, even better, use the strongly-typed helper:
#Html.DropDownListFor(m => m.group_id, ...)
Assuming you have a form field in your form with the name group_id like this and you want to set the selected value from your dropdown to that field for some reason,
#Html.HiddenFor(s=>s.group_id)
<div class="form-group">
#Html.DropDownList("groups",new SelectList(string.Empty, "Value", "Text"), "Choose...")
</div>
You can listen to the change event of the dropdown and get the selected option value and set to the group_id
$(function(){
$("#groups").change(function(e){
var v=$(this).val();
$("#group_id").val(v);
});
});
I am not sure why you are loading the dropdown content via javascript, but there are other better ways to render a dropdown and pass the selected value back to your controller as explained in this post.
Add a SelectedGroup property to your view model
public class CreateSomethingViewModel
{
public int SelectedGroup {set;get;}
public List<SelectListItem> Groups {set;get;}
}
and in your GET action, If you want to load the Groups, you can do it
public ActionResult Create()
{
var vm = new CreateSomethingViewModel();
//Hard coded for demo. You may replace with your db entries (see below)
vm.Groups = new List<SelectListItem> {
new SelectListItem { Value="1","Chase bank" },
new SelectListItem { Value="2","PNCbank" },
new SelectListItem { Value="3","BOA" }
};
return View(vm);
}
And in your view
#model CreateSomethingViewModel
#using(Html.BeginForm())
{
#Html.DropDownListFor(s=>s.SelectedGroup,Model.Groups)
<input type="submi" />
}
With this you do not need to use any js code ( Even if you load the dropdown content via javascript), when user changes the dropdown option value, It will be set as the value of the SelectedGroup property.
[HttpPost]
public ActionResult Create(CreateSomethingViewModel model)
{
// check model.SelectedGroup
// to do : Save and return/redirect
}

DropDownListFor Unobtrusive validation shows on empty form

I get validation message always when I open this page (even first time), even if I choose value in one of dropdown lists, message doesn't go away. If I choose values in both I can submit form but messages still doesn't go away.
Snippet is Linq to sql class and LanguageID and SnippetTypeID are ints, I assume this happens because I pass empty model to View so LanguageID and SnippetTypeID are null and AFAIK Linq to Sql classes have required on non-nullable ints.
How can I fix this so validation messages doesn't appear before user tries to submit form, and if one of dropdown lists get selected to remove validation message.
View
#model Data.Snippet
#using (Html.BeginForm("Save", "Submit", FormMethod.Post))
{
<h1 class="subtitle">Submit new snippet</h1>
<h4>Title</h4>
#Html.TextBoxFor(snippet => snippet.Title, new { #class = "form-field" })
<h4>Language</h4>
#Html.DropDownListFor(snippet => snippet.LanguageID, new SelectList(#ViewBag.Input.Languages, "ID", "Name", #Model.LanguageID), "Choose Language", new { #class = "form-select" })
<p>#Html.ValidationMessageFor(snippet => snippet.LanguageID , "You must choose language", new { #class= "validation-message"})</p>
<h4>Snipet type</h4>
#Html.DropDownListFor(snippet => snippet.SnippetTypeID, new SelectList(#ViewBag.Input.SnippetTypes, "ID", "Name", #Model.SnippetType), "Choose snippet type", new { #class = "form-select" })
<p>#Html.ValidationMessageFor(snippet => snippet.SnippetTypeID,"You must choose snippet type", new { #class= "validation-message"})</p>
<h4>Text</h4>
#Html.TextAreaFor(snippet => snippet.Text, new { cols = "20", rows = "10", #class = "form-field" })
<input type="submit" value="Submit Snippet" />
}
Controller
//Controllers are not finished Save() should have
//code to actually insert to db after I fix validation
// GET: /Submit/
//
public ActionResult Index()
{
Snippet model = new Snippet();
SubmitModel input = new SubmitModel();
ViewBag.Input = input;
return View(model);
}
public ActionResult Save(Snippet snippet)
{
return View();
}
Model
Model is Linq to Sql class.
Snippet
ID (int, identifier)
Title (string)
SnippetType (int, FK on table SnippetTypes)
LanguageID (int, FK on table Languages)
Text (string)
Alright,
So I think the reason it is failing is because of the custom CSS that you are adding. ValidationMessageFor will put a hidden class when the validation is successful.
if you want to add custom colors or something like that with you CSS i would consider applying the style to the wrapping p tag or adding a wrapping div/span and adding it to that.
You could probably define your messages on the view using only #Html.ValidationMessageFor(snippet => snippet.SnippetTypeID, "ErrorMessage"); However a more proper way is to take your Model and create Data Annotations for it.
Take a look at this article http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validation-with-the-data-annotation-validators-cs for more information about how to do model validation with Data Annotations.
Also I would consider passing in custom classes instead of your linq to sql class so that you can do custom validation based on the view. These custom classes are often refereed to as ViewModels.

Categories