Model
public class MyModel {
public string ItemXYZ { get; set; }
}
Controller
public ActionResult Edit(int? id)
{
var x = db.XYZs.Find(id);
ViewBag.Item_XYZ = new SelectList(new[] { "X", "Y", "Z"}, x.CurrentXYZ);
}
View
#Html.DropDownList("XYZ123", #ViewBag.Item_XYZ as SelectList, new { #class = "special-class" })
Problem
If I change my DropDownList to mach the name of the get set in my model, the selected value does not work.
#Html.DropDownList("ItemXYZ" ....)
If it matches the name of my ViewBag item, the SelectedItem doesn't work.
#Html.DropDownList("Item_XYZ" ....)
But, if I append 123 (for example), SelectedItem works just fine.
UPDATE
This is the same issue I am having, but I don't understand why or how to handle the return in my controller?
In Controller use the code as::
public ActionResult Edit(int? id)
{
var x = db.XYZs.ToList();
ViewBag.TestDropdown = new SelectList(x, "ValueField", "TextField", "DefaultSelected");
}
and in Client side to show Dropdown use this:
#Html.DropDownList("TestDropdown")
thats it.
May be this will help you.
Receive a parameter named XYZ123 in respective action.
Also include XYZ123 in Bind attribute of action.
Related
I have a modal popup used to update my form. There is a db field that is dependent upon the selection of another value on a popup. I would like to post that value to my form. Note that value is not on my popup. The ViewBag has the value I need but it is not in catalogPrice.
Help would be very much appreciated. Thanks.
[HttpPost]
public IActionResult AddCatalogPrice(CatalogPrice catalogPrice)
{
if (ModelState.IsValid)
{
var newNDCDescription = catalogPrice.NDCDescription;
var getNDC = (from n in Db.NationalDrugCodes
where n.NDCDescription == newNDCDescription
select new { n.NDCNumber }).ToList();
ViewBag.getNDC = getNDC;
Db.CatalogPrices.Add(catalogPrice);
Db.SaveChanges();
}
return RedirectToAction("ModalPopupCatalogPrice", "GTN");
}
I have hard time understanding assigning value to a property dynamically, means during run time so that i can retrieve/display value in a razor page. I have following programming logic to accomplish my task, however this (LmitedWords) property does not render or hold any value to be displayed. How do I assign a value to this property during run time.
public class Post
{
public string Content { get; set; }
[NotMapped]
public string LimitedWords { get; set; }
}
My controller code follow:-
public async Task<IActionResult> GetAllPosts()
{
var myLimitProperty = new Post();
var result = await _repository.GetAllPosts();
foreach (var post in result)
{
var limitContent = ContentExtension.ReturnLimitedDescription(post.Content, size);
myLimitProperty.LimitedWords = limitContent;
}
return View(result);
}
my contentextension helper method returns value as expected and during debug it does show that local variable "limitContent" has the value but it somehow does not assign it to LimitedWords property, which is a property in Post class.
In my Post class there are other properties as well and i want them to be displayed as it is saved in the database.
My Razor page does not display content as it is null:
<div>
<markdown markdown="#Model.LimitedWords">
</div>
Thanks!
Well based on what you have posted, the result holds the posts returned by the repository.
You loop through these posts, update the myLimitProperty local variable in the action and return the original collection.
Nothing is actually being updated on objects being sent to the view
Create a projection from the list, populating the desired properties that should be displayed in the view.
public async Task<IActionResult> GetAllPosts() {
var posts = await _repository.GetAllPosts();
var result = posts.Select(post => {
var limitContent = ContentExtension.ReturnLimitedDescription(post.Content, size);
var model = new Post() {
Content = post.Content;
LimitedWords = limitContent;
};
return model;
}).ToList();
return View(result);
}
I have a SelectList in my action method. The selected value for SelectList is coming from the action method parameter. The action and view are simple like below:
// Recipe Action
public ActionResult Recipe(int? recipeId)
{
ViewBag.RecipeID = new SelectList(_recipsRecipes, "RecipeID", "RecipeName", recipeId);
return View(new Recipe());
}
//Recipe View
#model RecipeDemo.Models.Recipe
#Html.DropDownList("RecipeID", (SelectList)ViewBag.RecipeID, string.Empty)
I'm using ActionLink below to call the Recipe action.
#Html.ActionLink("Recipe", "Recipe", "Home", new { recipeId = 2 }, null)
It works like I expect, the DropDownList is showing the selected value as the No. 2 (recipeId = 2) item.
Problem
When I change the Recipe action parameter by using route id, like below:
//Recipe View
public ActionResult Recipe(int? id)
{
ViewBag.RecipeID = new SelectList(_recipsRecipes, "RecipeID", "RecipeName", id);
return View(new Recipe());
}
//Recipe View (Same View as above)
#model RecipeDemo.Models.Recipe
#Html.DropDownList("RecipeID", (SelectList)ViewBag.RecipeID, string.Empty)
And I'm using ActionLink below to call the Recipe action.
#Html.ActionLink("Recipe", "Recipe", "Home", new { id = 2 }, null)
The DropDownList is NOT showing the selected value, (id = 2) item. The selection is instead empty.
But I have the correct id value in the SelectList. see below:
Why is this, does anyone know the explanation?
Update:
The model is below:
public class Recipe
{
public int RecipeID { get; set; }
public string RecipeName { get; set; }
}
Well that was certainly interesting. After first confirming the issue with the code you provided, I experimented around and believe I have the root cause. Basically, you are using the same variable name way to often and the model binder appears to be getting confused. You have RecipeId in your route, RecipeId in your View Model and RecipeId as the name of your view bag variable. By altering my variable names, the SelectList works as expected.
The primary issue is naming your SelectList RecipeId which matches a property in your model. When you send the new Recipe(), the model binder is attempting to use that value. In your first example, since you have RecipeId defined in the URL, it is getting it from there. In the second example, there is no RecipeId to pull from the URL and it is null in the model.
Controller
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
private List<Recipe> Recipes;
public HomeController()
{
Recipes = new List<Recipe>
{
new Recipe {RecipeId = 1, RecipeName = "Test - 1"},
new Recipe {RecipeId = 2, RecipeName = "Test - 2"},
new Recipe {RecipeId = 3, RecipeName = "Test - 3"},
};
}
public ActionResult Index(int? id)
{
ViewBag.MyList = new SelectList(Recipes, "RecipeID", "RecipeName", id);
return View(new Recipe());
}
}
}
Index View
#model MvcApplication1.Models.Recipe
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#Html.DropDownList("MyRecipeId", (SelectList)ViewBag.MyList)
Basically, vary your parameter names a little bit more to help prevent the model binder from getting confused and/or pulling information from the wrong place.
You can verify this in your second example by sending this in your return statement:
Return View(New Recipe{RecipeId = 3});
The option value with 3 will be selected regardless of what the actual Id sent was.
EDIT
An even better option would be to do what I said to do as an example above. By changing your Action to this:
public ActionResult Index(int? id)
{
ViewBag.MyList = new SelectList(Recipes, "RecipeID", "RecipeName");
return View(new Recipe(RecipeId = id));
}
You can leave your view unchanged. Now, the SelectList will pull from the model that you are sending.
I have a pretty simple scenario and I'm sure I'm just missing something obvious. I'm trying to use a ListBox to grab multiple Id's and add them to my model, but no matter what I do, the collection is always null. Here's the code:
The model collections:
public IEnumerable<Model.UserProfile> TravelBuddies { get; set; }
public IEnumerable<int> SelectedTravelBuddies { get; set; }
I populate the TravelBuddies collection in my controller.
The view code:
<div class="module_content">
#if (Model.TravelBuddies.Count() > 0)
{
#Html.ListBoxFor(m => m.SelectedTravelBuddies, new MultiSelectList(Model.TravelBuddies, "Id", "FullName"))
}
else
{
<span>You don't currently have any travel buddies (people who were with you on this trip). Don't worry, you can add some to this trip later if you'd like.</span>
}
</div>
The select list is populated in my view. No problem there. But once I select multiple items and submit my form, the Model.SelectedTravelBuddies collection is always null. Am I missing something obvious? It's been a long night of coding.
Update: Added Controller Code
[HttpGet]
public ActionResult New()
{
Model.Trip trip = new Model.Trip();
ITripService tripService = _container.Resolve<ITripService>();
IUserAccountService userService = _container.Resolve<IUserAccountService>();
int userProfileId = userService.GetUserProfile((Guid)Membership.GetUser().ProviderUserKey).Id;
trip.TripTypes = new SelectList(tripService.GetTripTypes(), "Id", "Name");
trip.TravelBuddies = userService.GetTravelBuddies(userProfileId);
tripService.KillFlightLegTempStorage();
return View(trip);
}
[HttpPost]
public ActionResult New([Bind(Exclude = "TripTypes")] Model.Trip trip)
{
ITripService tripService = _container.Resolve<ITripService>();
if (!ModelState.IsValid)
{
tripService.KillFlightLegTempStorage();
return View(trip);
}
int tripId = tripService.CreateTrip(trip, (Guid)Membership.GetUser().ProviderUserKey);
tripService.KillFlightLegTempStorage();
return RedirectToAction("Details", "Trip", new { id = tripId });
}
Ok so you are binding to SelectedTravelBuddies. When your list is rendered, what is it's name? It's been a long night for me too :) want to make sure it matches the model. Also are you sure the list is in the form element so they are posted?
Can someone help me with getting values from a dropdownlist in asp.net mvc?
I can get values from textboxes,etc...but,how do I get these 2 things...
Getting Selected Item Value of the drop down list from the controller class
Getting all the list of items of the drop down list from the controller class
Thanks
You can get the selected value from a drop down list the same way as you do for text boxes.
Using default model binding
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(string MyList) {
//MyList will contain the selected value
//...
}
or from a FormCollection
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(FormCollection form) {
string val = form["MyList"];
//...
}
or from the request
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(string MyList) {
string val = Request.Form["MyList"]; //or
val = Request["MyList"];
//...
}
Where your drop down list is named "MyList".
<%= Html.DropDownList("MyList", MyItems) %>
or straight HTML
<select name="MyList">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
</select>
The browser will only submit the selected value from the drop down list and not all the other values. To get the list of all the other items you should invoke the code that populated the list in the first place (assuming you used Html.DropDownList()).
Update
[AcceptVerbs(Http.Get)]
public ActionResult GetValueExample() {
ViewData["MyItems"] = GetSelectList();
return View();
}
[AcceptVerbs(Http.Get)]
public ActionResult GetValueExample(string MyList) {
//MyList contains the selected value
SelectList list = GetSelectList(); //list will contain the original list of items
//...
}
private SelectList GetSelectList() {
Dictionary<string, string> list = new Dictionary<string, string>();
list.Add("Item 1", "1");
list.Add("Item 2", "2");
list.Add("Item 3", "3");
return new SelectList(list, "value", "key");
}
//...
<%= Html.DropDownList("MyList", ViewData["MyItems"] as SelectList) %>
Well it's hard to answer correctly since you've given so little information, but in general you get the selected value in the post method of the Controller.
Something like this might explain it better:
Consider having this dropdownlist:
//instantiate the dropdownlist in the controller method.
public ActionResult Create() {
List<string> items = new List<string>() {"first", "second", "third"};
SelectList SomeSelectItems = new SelectList(items);
ViewData["list"] = SomeSelectItems;
return View();
}
<%= Html.DropDownList("DDL", (SelectList)ViewData["list"]) %>
In your controller you would get the value of the dropdownlist like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(string DDL)
{
string theValue = DDL;
return View();
}
To get all the values from the dropdownlist would be the same as putting them into the selectlist in the first place. I will assume you have a method that is called to fill the dropdownlist with items. Simply call this method from within the controller and handle the values appropriately.
I think you need to rethink this. The values for the dropdown should come from the controller and sent to the view for display in the dropdown to allow the user to select. Then the page form sends the selected value back to the controller. Data should always be on the server side and the view is just for display.