I'd like to create a dropdownlist from following structure
List<KeyValuePair<long, string>> sponsori =
new List<KeyValuePair<long, string>>();
Now I want the selectlist to have the pair's long as data value, the string as text value and the selected item, if I have only access to the long of the selected item.
THanks in advance.
In your action code
yourViewModel.Sponsori= new SelectList(sponsori, "Key", "Value")
In your view code
<%=Html.DropDownList("yourSelectid", Model.Sponsori) %>
ViewData["selectList"] = new SelectList(sponsori, "Key", "Value");
And then on the page:
<%= Html.DropDownList("selectList") %>
You can also check out Rendering a Form in ASP.NET MVC Using HTML Helpers for a similar example (and more documentation).
Related
I have the following form:
<li>
<% using (Html.BeginForm("TestMethod", "MyController", FormMethod.Post, new {id = "TestMethod"}))
{%>
<%= Html.Hidden("model", Model.MyListOfObjects) %>
<%}%>
Test
</li>
And the javascript function for the onclick is as follows:
function SubmitForm() {
document.forms["TestMethod"].submit();
}
I am trying to pass the list of objects from the view into the controller, but i have yet managed to get this to work. My Controller function is:
[Authorize]
[HttpPost]
public ActionResult TestMethod(List<Objects> model)
{
dynamic Expando = new ExpandoObject();
Expando.test = model;
return View(Expando );
}
When I view the List of objects in the debugger it always displays "System.Collections.Generic.List`1[]" with no actual objects inside.
So my question is what should I be doing to pass a List of objects into a controller?
I have also tried:
<% using (Html.BeginForm("TestMethod", "MyWork", FormMethod.Post, new {id = "TestMethod"}))
{%>
<% int itemx = 0; %>
<% foreach (var x in Model.MyListOfObjects)
{%>
<%= Html.Hidden("model"+"["+itemx+"]", x) %>
<%itemx++; %>
<% } %>
<%}%>
You cannot just put List<object> as action parameter and expect the model binder to be able to automagically guess what object types you want to put there. You will need to write a custom model binder if you wanted to handle multiple sub-types as illustrated in this post.
And if you want to use a single type for the list such as List<MyViewModel> then simply loop through each element of the list (respecting the convention) and for each element build a hidden field for each property that you want to bind.
But since those are hidden fields, I guess that the user is not supposed to modify them. In this case those hidden fields have nothing to do in your view. Let's not reinvent the ViewState that we were all so happy to get rid of when we moved to ASP.NET MVC from classic WebForms. Simply put a hidden field containing an unique id that will allow you to refetch the corresponding list elements in the POST action given this unique id from wherever you fetched them initially (your database or something I suppose).
You need to have one hidden element for each object in the list, and named model[0], model[1], etc.
I am new to mvc and i need some help.
I have this model class:
Public Class PostCategories
Public Property ID() As Integer
Public Property Name() As String
Public Property Slug() As String
Public Property ParentID() As Integer
and I have this dropdownlist in my view:
#Html.DropDownList("IDList", New SelectList(Model, "Id", "ID"), "Selected Parent")
Instead of ID, I'd like to put the Name in the dropdownlist and save the ID to the db. How am i supposed to do it? Need help pls.
Assuming your View Model is a list of PostCategories then just use:
#Html.DropDownList("IDList", New SelectList(Model, "ID", "Name"), "Selected Parent")
As Beyers said, it should be sufficient to change your code to
#Html.DropDownList("IDList", New SelectList(Model, "ID", "Name"), "Selected Parent")
where the second parameter of the SelectList constructor is the value of the selected item you want to be passed upon form submit, and must reflect the name of one of your Model properties, therefore must be "ID" and not "Id".
The second parameter is the item's name displayed in the dropdown, in this case you should use "Name" as it's probably the property you want to use.
Optionally you can pass in a fourth parameter that is the selected value at page load time.
Another approach would be to build your SelectList in the controller and pass it using the ViewBag like this:
ViewBag.PostCategoriesId = new SelectList(yourPostCategoriesList, "ID", "Name");
and then in the View your code would be like:
#Html.DropDownList("PostCategoriesId", string.Empty)
I have a little problem. I use the Html.DropDownListFor helper to render a dropdown list to the client.
But I can't set the selected value in dropdown list.
<%= Html.DropDownListFor(model => Model.CalculationClassCollection,
new SelectList(Model.CalculationClassCollection, "ID", "Name", 3 ),
new { id = "ddCalculationClass" })%>
Anybody can help me?
If the SelectList is not a member of my Model, I'd use <%= Html.DropDownList("listBoxID", new SelectList(Model.CalculationClassCollection, "ID", "Name", 3 ))%>
It is one of the overloaded methods. I think it is the method with a parameter something like default. Sorry I am not in front of dev PC right now so I can't tell you exactly which method it is.
I have a dropdownlist that I populate with some stuff:
In my controller
ViewData["SourceModelList"] = new SelectList(_modelService.GetAllModels(), "Id", "Description");
in my view
<% using (Html.BeginForm("Compare", "Home")) { %>
<p>
<%=Html.DropDownList("SourceModelList")%>
</p>
<p>
<input type="submit" value="Compare" />
</p>
<% } %>
And this renders lovely. Now when I post back to my 'compare' action, how do I find out which item was selected in the drop down?
The name "SourceModelList" should correspond with the name of a field in your ViewModel, so that the binder has something to bind the value of the dropdown to.
Alternatively, you can pluck the value out of the FormCollection object, if your view is not strongly-typed.
The NerdDinner Tutorial goes into this process in greater detail:
NerdDinner Step 5: Create, Update, Delete Form Scenarios
http://nerddinnerbook.s3.amazonaws.com/Part5.htm
You can use any of the regular methods for getting items from a form in ASP.NET MVC: FormCollection, Request object, binding to a specific model or having an action which takes a string SourceModelList parameter.
You can do:
int value = Convert.ToInt32(Request.Form["SourceModelList"]);
Or by ModelBinders just making sure that your model have a property
public int SourceModelList {get; set;}
And the ModelBinder will get it for you.
Or, but less likely:
public ActionResult Name(FormCollection f, int SourceModelList)
I have the following ActionLink in my view
<%= Html.ActionLink("LinkText", "Action", "Controller"); %>
and it creates the following URL http://mywebsite.com/Controller/Action
Say I add an ID at the end like so: http://mywebsite.com/Controller/Action/53 and navigate to the page. On this page I have the markup I specified above. Now when I look at the URL it creates it looks like this:
http://mywebsite.com/Controller/Action/53 (notice the addition of the ID)
But I want it to remove the ID and look like it did originally, like this http://mywebsite.com/Controller/Action (notice no ID here)
Any ideas how I can fix this? I don't want to use hard coded URLs since my controller/actions may change.
The solution is to specify my own route values (the third parameter below)
<%= Html.ActionLink("LinkText", "Action", "Controller",
new { id=string.Empty }, null) %>
It sounds like you need to register a second "Action Only" route and use Html.RouteLink(). First register a route like this in you application start up:
routes.MapRoute("ActionOnly", "{controller}/{action}",
new { controller = "Home", action = "Index" } );
Then instead of ActionLink to create those links use:
Html.RouteLink("About","ActionOnly")
The problem is the built in methods take input from the URL you are currently on as well as what you supply. You could try this:
<%= Html.ActionLink("LinkText", "Action", "Controller", new { id = ""}) %>
That should manually wipe the id parameter.
Don't know why, but it didn't work for me (maybe because of Mvc2 RC). Created urlhelper method =>
public static string
WithoutRouteValues(this UrlHelper helper, ActionResult action,params string[] routeValues)
{
var rv = helper.RequestContext.RouteData.Values;
var ignoredValues = rv.Where(x=>routeValues.Any(z => z == x.Key)).ToList();
foreach (var ignoredValue in ignoredValues)
rv.Remove(ignoredValue.Key);
var res = helper.Action(action);
foreach (var ignoredValue in ignoredValues)
rv.Add(ignoredValue.Key, ignoredValue.Value);
return res;
}
If you either don't know what values need to be explicitly overridden or you just want to avoid the extra list of parameters you can use an extension method like the below.
View
The implementation details are in this blog post
I explicitly set the action name as "Action/". Seems a little like a hack but it's a quick fix.
#Html.ActionLink("Link Name", "Action/", "Controller")
Another way is to use ActionLink(HtmlHelper, String, String, RouteValueDictionary) overload, then there are no need to put null in the last parameter
<%= Html.ActionLink("Details", "Details", "Product", new RouteValueDictionary(new { id=item.ID })) %>
The overloads of Html.ActionLink are changed on the later versions of MVC. On MVC 5 and above. This is how to do this:
#Html.ActionLink("LinkText", "Action", "Controller", new { id = "" }, null)
Note I passed "" for id parameter and null for HTMLATTRIBUTES.
I needed my menu links to be dynamic. Rather than implement a lot of extra code and routing for every single page I simple dispensed with the HTML helper.
#item.MenuItemName