I am populating a dictionary object with key value pairs like this..
Dictionary<string, string> twoValues = new Dictionary<string, string>();
foreach (var item in query)
{
twoValues.Add(item.Name, item.Id);
}
return twoValues;
I am returning these value pairs to the controller and populating a MVC model (selectlists)
model.Names = new SelectList(twoValues.Keys);
model.Ids = new SelectList(twoValues.Values);
return model;
In the view I have an action link and a drop down. Drop down is populated with key values of the dictionary (in this case, key is text names, and value is ids)
//Action link
<%=Html.ActionLink("link", "Method", "Controller", new { Id = ?? })%>
//Drop down
<%=Html.DropDownList("names", Model.Names, "")%>
How do I pass the Id associated with the selected Name in drop down to the controller via action link?
I tried having another drop down list next to names with the ids .. but somehow I need to maintain the link between the two drop downs.. since I am separating the dictionary key value pairs in the view for display...
I can have something like...
//Action link
<%=Html.ActionLink("link", "Method", "Controller", new { Id = ?? })%>
//Drop down
<%=Html.DropDownList("names", Model.Names, "")%>
<%=Html.DropDownList("ids", Model.Ids, "")%>
How do I pass the id via the action link for the selected 'Name' drop down list.
You need to do some javascript trick on the click event. Read the selected value of the drop down and build the url and navigate to that.
#Html.ActionLink("Link","Method","Controller",null,new { #class="hackLink"})
<script type="text/javascript">
$(function(){
$(".hackLink").click(function(e){
e.preventDefault(); //Prevent default link click behaviour
var item=$(this);
var selectedVal=$("#names").val();
var newUrl=item.attr("href")+"?id="+selectedVal;
window.location.href=newUrl;
});
});
</script>
Assuming names is the ID of your DropDown.
Alternatively, you can listen to the change event of the Dropdown and then set the value href attribute of the link.
I would recommend creating one dropdown that will have the value of the options equal to your id field and the text equal to your names. You should be able to create it using something this:
Controller:
IEnumerable<SelectListItem> items = yourQueryCode.Select(c => new SelectListItem
{
Value = c.ID.ToString(),
Text = c.Name
});
ViewBag.Names = items;
HTML:
<%= Html.DropDownList("Names", (IEnumerable<SelectListItem>) ViewBag.Names) %>
This will allow you to get the ID linked to the name as the value of the dropdown when you do $('#dropdown').val().
Preferably you would have the SelectList as part of your model that you return to the view, but the above will work as well. There will only have to be a few minor changes when you switch to returning via the model and the transition is pretty simple. Hopefully this is enough to get you headed in the right direction.
Related
My controller code:
ViewBag.ddlprincepal = new SelectList(objentity.ddlPrincipal(), "PrincipalID", "PrincipalName");
ViewBag.ddlprincepalselected = new SelectListItem { Text = inventoryDetailobj[0].PrincipalName, Value = (inventoryDetailobj[0].PrincipalID).ToString(),Selected=true };
My view the code:
#Html.DropDownList("ddlprincepal",ViewBag.ddlprincepal as SelectList ,ViewBag.ddlprincepalselected as string , new { #id = "ddlprincepal" })
Well you can do this by Jquery and it has only few lines of code. Since I don't know what text you are having before edit, I assume something such as Name.
We need to first select the dropdownlist and then on the edit button click, we need to send the text value into the dropdownlist as its value.
So the code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$('.EditBtn').on('click',function(){
// this is the text value you show in label form (before edit)
var lblObj = $("#lblName");
// this is your dropdown while edit mode.
var dropdwn = $("#ddlprincepal");
dropdwn.val(lblObj.html()); // this will bring your text value into the dropdownlist while edit mode.
});
Hope this helps.
i have found the solustion
View//
#Html.DropDownListFor(model => model.PrincipalID, ViewBag.ddlprincepal as SelectList, "--select--", new { #id = "ddlprincepal" })
Hello basically I want a dropdownlist to display a list of employee names when the admin or whoever in management is using it selects a name the chart must display. Is this possible? If so please help me...
public ActionResult CharterColumn()
{
var results = (from c in db.Clockcards select c);
// the employeeid is a foreign key in the clockcards table
// i want to get the name from the employee table
// and display only that employees hours worked for the months
var groupedByMonth = results
.OrderByDescending(x => x.CaptureDate)
.GroupBy(x => new { x.CaptureDate.Year, x.CaptureDate.Month }).ToList();
List<string> monthNames = groupedByMonth
.Select(a => a.FirstOrDefault().CaptureDate.ToString("MMMM"))
.ToList();
List<double> hoursPerMonth = groupedByMonth
.Select(a => a.Sum(p => p.Hours))
.ToList();
ArrayList xValue = new ArrayList(monthNames);
ArrayList yValue = new ArrayList(hoursPerMonth);
new Chart(width: 800, height: 400, theme: ChartTheme.Yellow)
.AddTitle("Chart")
.AddSeries("Default", chartType: "Column", xValue: xValue, yValues: yValue)
.Write("bmp");
return null;
}
And this is my view
<div>
<img src= "#Url.Action("CharterColumn")" alt="Chart"/>
</div>
You can listen to the change event on the dropdown list, read the selected option value (assuming it is the employee id) and pass that to the action method which return the chart data for that employee record and update the image tag's src attribute value.
<select id="employeeList">
<option value="0">None</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<div>
<img id="chart" data-url="#Url.Action("CharterColumn")" alt="Chart" />
</div>
You can see that i set an html5 data attribute to the image tag and i set the value of that to the relative path to the action method using Url.Action method .We will read this value later in javascript.
I hard coded the HTML for the SELECT element. You can replace it with using the employee data from your table using Html.DropDownList or Html.DropDownListFor helper methods as needed.
Now, update your action method to accept the employee id value as a parameter
public ActionResult CharterColumn(int employeeId)
{
//use employeeId to filter the results
var results = db.Clockcards.Where(s=>s.EmployeeId==employeeId).ToList();
//your existing code to return the chart
}
Now the javascript to handle the change event.
$(document).ready(function () {
loadChart($("#employeeList").val()); // initial load of the chart with selected option
$("#employeeList").change(function () {
var employeeId = $(this).val();
loadChart(employeeId);
});
function loadChart(employeeId) {
var imgSrc = $("#chart").data("url") + "?employeeId=" + employeeId;
$("#chart").attr("src", imgSrc);
}
});
This should work assuming you do not have any other script errors in your page.
ASP.NET MVC5
I have a combobox in a grid (InLine Edit):
columns.Bound(x=>x.AccountID).EditorTemplateName("MyTemplate")
Where MyTemplate is in /Shared
There are millions of Accounts.
When I try to edit the combo box in a grid and choose a new value, the ID of the Account, not the name, appears. This is because of course the name of the account is not immediately present so in the Read().Data() of the ComboBox.Datasource I need to send additional data; the AccountID.
My ComboBox Template looks like this:
.DataSource(source=>
source.Read(read =>
read.Action("ReadAccounts".....)
.Data("HERE IS WHERE I NEED TO SEND THE ACCOUNT ID AS EXTRA DATA
WHEN THIS CBO TEMPLATE IS IN A GRID")
Thank you
Here's the Combo Box defined in a partial view in ~/Views/Shared/EditorTemplates/ComboBoxTemplate
#(Html.Kendo().ComboBox()
.Name("AcctName")//must match Field Name that is being edited
.HtmlAttributes(new { style = "width:250px" })
.DataTextField("AcctName")
.DataValueField("AcctCd")
.Filter(FilterType.StartsWith)
.AutoBind(true)
.MinLength(3)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetCombo", "GridPost").Data("OnAdditionalData");
})
.ServerFiltering(true);
})
)
Here's the view and controller action
columns.Bound(x => x.AcctName).Title("Acct Name").EditorTemplateName("ComboBoxTemplate");
function OnAdditionalData() {
var entityGrid = $("#ProposalGridX").data("kendoGrid");
var selected = entityGrid.dataItem(entityGrid.select());
//if the id is off the Grid Row and not the ComboBox
//select the row and pull the fields
//selected.PropertyName
return {
text : $("#AcctName").data("kendoComboBox").text(),
val : $("#AcctName").data("kendoComboBox").value()
};
}
public JsonResult GetCombo(string text, string val)
{
List<PortfolioViewModel> model = new AUMBusiness().GetAum(DateTime.Now);
if (!string.IsNullOrEmpty(text))
{
model = model.Where(x => x.AcctName.StartsWith(text)).ToList();
}
return Json(model, JsonRequestBehavior.AllowGet);
}
Like with any Ajax calls, placing break points in the code might prevent the widget from performing as intended. For ex. using incell editing while clicking the Field to edit, if you place a breakpoint in GetCombo the ComboBox editor template will not default correctly to that value.
I have a razor (cshtml) file with a dropdownlistfor:
#Html.DropDownListFor(model => model.x_nme, (SelectList) ViewData["Y"]);
The SelectList is formed in the controller as:
var = new SelectList(xList, "id", "x_nme", current.id);
ViewData["Y"] = y_var;
I want the model to bind to the "x_nme" attribute, which displays correctly in the dropdown, but instead it binds to the id attribute.
I need the id attribute as this dropdown fills several fields in the form using javascript/ajax/jquery and I could as an alternative bind to a hidden field to get the name correct.
I was wondering if there is a way to directly bind the model => model.x_nme to the text in the drop-down instead of the underlying id w/o having to have a hidden field.
Thanks in advance.
ViewData["Y"] = new SelectList(xList, "Text", "Text");
Then there is only text on the dropdown, so it will be selected!
This actually works!
I have following problem. In my view model I defined some list properties as follows:
public class BasketAndOrderSearchCriteriaViewModel
{
List<KeyValuePair> currencies;
public ICollection<KeyValuePair> Currencies
{
get
{
if (this.currencies == null)
this.currencies = new List<KeyValuePair>();
return this.currencies;
}
}
List<KeyValuePair> deliverMethods;
public ICollection<KeyValuePair> DeliveryMethods
{
get
{
if (this.deliverMethods == null)
this.deliverMethods = new List<KeyValuePair>();
return this.deliverMethods;
}
}
}
This view model is embedded in another view model:
public class BasketAndOrderSearchViewModel
{
public BasketAndOrderSearchCriteriaViewModel Criteria
{
[System.Diagnostics.DebuggerStepThrough]
get { return this.criteria; }
}
}
I use 2 action methods; one is for the GET and the other for POST:
[HttpGet]
public ActionResult Search(BasketAndOrderSearchViewModel model){...}
[HttpPost]
public ActionResult SubmitSearch(BasketAndOrderSearchViewModel model){...}
In the view I implement the whole view model by using the EditorFor-Html Helper which does not want to automatically display DropDownLists for List properties!
1. Question: How can you let EditorFor display DropDownLists?
Since I could not figure out how to display DropDownLists by using EditorFor, I used the DropDownList Html helper and filled it through the view model as follows:
public IEnumerable<SelectListItem> DeliveryMethodAsSelectListItem()
{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem()
{
Selected = true,
Text = "<Choose Delivery method>",
Value = "0"
});
foreach (var item in this.DeliveryMethods)
{
list.Add(new SelectListItem()
{
Selected = false,
Text = item.Value,
Value = item.Key
});
}
return list;
}
My 2. question: As you can see I pass my view model to the action metho with POST attribute! Is there a way to get the selected value of a DropDownList get binded to the passed view model? At the moment all the DropDownList are empty and the selected value can only be fetched by the Request.Form which I definitely want to avoid!
I would greatly appreciate some ideas or tips on this!
For those like me that got to this post these days I'd recommend you to fully download the tutorial from http://www.asp.net/mvc/tutorials/mvc-music-store-part-1 which covers this and most of the common techniques related with .NET MVC applications.
Anyway Really usefull your post and answers man (If I could vote you I would :)
Let's try to take on this one:
Answer to Question 1: How can you let EditorFor display DropDownLists?
When you call Html.EditorFor() you can pass extra ViewData values to the EdiorTemplate View:
<%: Html.EditorFor(model => Model.Criteria, new { DeliveryMethods = Model.DeliveryMethods, Currencies = Model.Currencies}) %>
Now you have ViewData["DeliveryMethods"] and ViewData["Currencies"] initialized and available inside your EditorTemplate.
In your EditorTemplate you somehow need to call and convert those entries into DropDowns / SelectLists.
Assuming you've got an ascx file of type System.Web.Mvc.ViewUserControl<BasketAndOrderSearchCriteriaViewModel> you could do the following:
<%: Html.LabelFor(model => model.DeliveryMethods) %>
<%: Html.DropDownList("SelectedDeliveryMethod", new SelectList(ViewData["DeliveryMethods"] as IEnumerable, "SelectedDeliveryMethod", "Key", "value", Model.SelectedDeliveryMethod)) %>
Same goes for the Currencies.
<%: Html.LabelFor(model => model.Currencies) %>
<%: Html.DropDownList("SelectedCurrency", new SelectList(ViewData["Currencies"] as IEnumerable, "SelectedDeliveryMethod", "Key", "value", Model.SelectedCurrency)) %>
This setup will make your DeliveryMethodAsSelectListItem() obsolete and you can use any kind of list. Means you are not bound to KeyValuePairs. You'll just need to adjust your call on Html.DropDownList() from now on.
As you can see, I have introduced some new properties to your BasketAndOrderSearchCriteriaViewModel:
Model.SelectedDeliveryMethod
Model.SelectedCurrency
They are used to store the currently selected value.
Answer to Question 2: Is there a way to get the selected value of a DropDownList get binded to the passed view model?
In the EditorFor template we are passing the newly created Model.SelectedDeliveryMethod and Model.SelectedCurrency properties as the SelectedValue Parameter (See 4th Overload of the DropDownList Extension Method).
Now that we have the View doing it's job: How can we get the currently selected value inside the POST Action?
This is really easy now:
[HttpPost]
public ActionResult SubmitSearch(BasketAndOrderSearchViewModel model)
{
...
var selectedDeliveryMethod = model.Criteria.SelectedDeliveryMethod;
var selectedCurrency model.Criteria.SelectedDeliveryMethod;
...
}
Note: I don't have an IDE to test it right now, but it should do the trick or at least show you in which direction to go.