I have the following class:
public class Note : TableServiceEntity
{
public string Description { get; set; }
public string NoteDetailsJSON { get; set; }
}
It contains short descriptions that I would like to put into a select list in my view.
I get the data from the table like this.
Notes = noteTable.GetAll()
I have my viewmodel look like this:
public IEnumerable<Note> Notes { get; set; }
However when I try to populate my select box I get only the following:
#Html.DropDownListFor(
x => x.Level,
new SelectList(Model.Notes, "Description", "Description"),
new { style = "display: inline;" }
)
<select id="Level" name="Level" style="display: inline;"><option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
</select>
Some help on how to populate the select box would be much appreciated.
I don't get what your question or problem is. Most probably noteTable.GetAll() simply returns empty objects.
So assuming you have the following view model which contains a list of notes:
public class MyViewModel
{
public string Level { get; set; }
public IEnumerable<Note> Notes { get; set; }
}
and your controller action properly populates this model:
public ActionResult Index()
{
var model = new MyViewModel
{
Notes = noteTable.GetAll().ToList() // make sure that this returns some data
};
return View(model);
}
obviously the best way to ensure that your problem is not in the data source is to initially hardcode some data:
public ActionResult Index()
{
var model = new MyViewModel
{
Notes = Enumerable.Range(1, 5).Select(x => new Note
{
Description = "note description " + x
})
};
return View(model);
}
in your view you should be able to display the dropdownlist:
#model MyViewModel
#Html.DropDownListFor(
x => x.Level,
new SelectList(Model.Notes, "Description", "Description"),
new { style = "display: inline;" }
)
Related
let me know whats wrong here , i am unable to save after selecting from drop down and clicking on save
<label asp-for="application.number" class="control-label"></label>
<select class="form-control" name="Tower">
<option>Select Tower</option>
<option>numbers</option>
<option>1</option>
<option>2</option>
<option>3</option>
i think i am getting error in below models
#Html.DisplayFor(modelItem => item.Tower)
You can use below code to generate dropdown:
#Html.DropDownList("Tower",new SelectList(#ViewBag.TowerList, "TowerId","TowerName"),"Select Tower", new { #class= "form-control"})
i am unable to save after selecting from drop down and clicking on save
You can set value attribute for <option> elements. Besides, you can refer to the following example to modify your code.
<form method="post">
<label asp-for="application.number" class="control-label"></label>: #Model.application.number
<select class="form-control" name="Tower">
<option>Select Tower</option>
<option>numbers</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="submit" value="Save" />
</form>
In page model class
public class TestModel : PageModel
{
[BindProperty]
public int Tower { get; set; }
public MyClass application { get; set; }
public void OnGet()
{
application = new MyClass { number = 0 };
}
public IActionResult OnPost()
{
//code logic here to save the selected value
application = new MyClass { number = Tower };
return Page();
}
}
public class MyClass
{
public int number { get; set; }
}
Test Result
I have a drop down list that I want to render a partial view depending on what item is chosen. For this, I am using jquery and MVC 5. After having put breakpoints in my controller, my Url.Action() call doesn't seem to be getting there when I change the dropdown selection. I'm not sure I understand how to use route values correctly so that could be it. This is what I've got:
Relevant part of starting view
<div>
#if (role == "admin")
{
<p>Choose state to view:</p>
<select id="stateList">
<option value="AL">Alabama</option>
<option value="AR">Arkansas</option>
<option value="DE">Delaware</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="IA">Iowa</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="MD">Maryland</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="NC">North Carolina</option>
<option value="NE">Nebraska</option>
<option value="NJ">New Jersey</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="SC">South Carolina</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="VA">Virginia</option>
<option value="WV">West Virginia</option>
</select>
<div id="#partialPlaceHolder">
</div>
}
JQuery to get to controller
//Load partial view when an admin changes the state selection
$('#stateList').change(function () {
var selection = $(this).val();
var url = '#Url.Action("StateData", "Visualizations")' + '?StateID=' + selection;
//url ends up looking like this: /Visualizations/StateData?StateID=IA (or some other state abbreviation)
$("#partialPlaceHolder").load(url, function () {
console.log("it worked");
});
});
Model
public class VisualizationModels
{
public String StateID { get; set; }
}
Controller for generating partial view
public ActionResult StateData(string stateID)
{
VisualizationModels vm = new VisualizationModels();
vm.StateID = stateID;
return PartialView("_SpecificStateData", vm);
}
UPDATE
Oddly enough, if I use $.get instead of #Url.Action, I will actually hit the controller action, it just won't render the partial view now for some reason...
//Load partial view when an admin changes the state selection
$('#stateList').change(function () {
var selection = $(this).val();
var url = '/Visualizations/StateData?StateID=' + selection;
$.get(url, function (data) {
$('#partialPlaceHolder').html(data);
});
Cannot you use something like this
var url = '#Url.Action("StateData", "Visualizations", new { StateID = selection})'
instead of
var url = '#Url.Action("StateData", "Visualizations")' + '?StateID=' + selection;
and check if this is working. Because if your parameter would not be passed correctly. Your route handler will not able to map correct action method.
I figured it out... it's the stupidest, peskiest little issue. In my main view (at the top of my original post) I had typed the id of my div wrong...
Wrong:
<div id="#partialPlaceHolder"></div>
Right:
<div id="partialPlaceHolder"></div>
Everything is working as expected now. Final JS looks like this:
//Load partial view when an admin changes the state selection
$('#stateList').change(function () {
var selection = $(this).val();
var url = '#Url.Action("StateData", "Visualizations", new { StateID = "_state" })'.replace("_state", selection);
$("#partialPlaceHolder").load(url, function () {
console.log("it worked");
});
});
I'm trying to add the attribute selected to an option inside a select, something like: <option value="item" selected>item</option>, but in an strange event the text selected is deleted when rendering the page.
For example I have the following code:
<select
class="form-control"
name="searchCode">
<option value="0"> Nothing Selected</option>
#foreach (string str in results) {
string sel = "";
if (str.Equals(searchCode)) {
sel = "selected";
}
<option
value="#str"
#sel>
#str
</option>
}
</select>
In this if searchCode == str then the #sel is set as "selected" but the problem is that when the site is rendered the #sel attribute is not printed.
For example, it should print:
<select>
<option value="a">a</option>
<option value="b" selected>b</option>
<option value="c">c</option>
</select>
But instead it prints:
<select>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
If I change my code to this:
<select
class="form-control"
name="searchCode">
<option value="0"> Nothing Selected</option>
#foreach (string str in results) {
string sel = "";
if (str.Equals(searchCode)) {
sel = "selected";
}
<option
value="#str"
#sel>
#str - #sel
</option>
}
</select>
I'll get something like this:
<select>
<option value="a">a - </option>
<option value="b">b - selected</option>
<option value="c">c - </option>
</select>
So the attribute selected is correctly calculated but it's not printed as it should.
Any ideas on what's happening?
It appears to be a bug: https://github.com/aspnet/Mvc/issues/3733
What I did is to change option as !option.
<select
class="form-control"
name="searchCode">
<option value="0"> Nothing Selected</option>
#foreach (string str in results) {
string sel = "";
if (str.Equals(searchCode)) {
sel = "selected";
}
<!option
value="#str"
#sel>
#str - #sel
</!option>
}
</select>
1) create class for search criteria
public class SearchCriteria
{
public string searchCode { get; set; }
public List<string> results { get; set; }
}
2) add the default option before binding the list
var searchCriteriaObj = new SearchCriteria { searchCode = "bla bla bla" };
searchCriteriaObj.results = searchManager.getResults(searchCode);
searchCriteriaObj.results.Insert(0, " Nothing Selected");
3) bind the object by passing it (Controller) after getting the results.
ViewBag.criteria = searchCriteriaObject;
4) View page:
<select asp-for="ViewBag.criteria.searchCode"
asp-items="ViewBag.criteria.results">
</select>
How can I add a simple validation in my code? If value = 0 I don't want the controller to process the form. If anything else is selected except 0, I want the controller to process the form.
#using (Html.BeginForm("GenerateReport", "Admin", FormMethod.Get))
{
<select id="reportId" name="reportId" class="form-control">
<option value="0">Select</option>
<option value="1">Religion</option>
<option value="2">Address</option>
<option value="3">Job</option>
<option value="4">Degree</option>
<option value="7">Age</option>
</select>
<input type="submit" value="Print" id="rlist_type" />
}
This article provides basic information on ASP.NET MVC 5 validation
http://www.asp.net/mvc/overview/getting-started/introduction/adding-validation
I would leave the value for the first option empty then add a [Required] attribute on the object that I was using to capture the form post.
public class AdminScreenFormPost
{
[Required]
public int reportId { get; set; }
}
Inside the controller add
if (!ModelState.IsValid)
{
return View();
}
In the razor view add this so it will displays the validation results
#Html.ValidationSummary(true)
I would also look into ModelState.AddModelError
ModelState.AddModelError("MyDropDownListKey", "Please Select");
I'm new at programming in MVC, so I ran into this problem...
I have the following selectBox:
<select class="span5" id="selectBox">
<option>Month</option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
How do I get the selected value into a model?
Start by creating your select list in a ViewModel:
public class whatever {
public List<SelectListItem> MonthList {get;set;}
public string SelectedMonth {get;set;}
public whatever()
{
MonthList = new List<SelectListItem>();
MonthList.Add(new SelectListItem{
Text = "January",
Value = "January"
});
}
}
Then in your view you can just use the drop down razor helper:
#Html.DropDownListFor(m => m.SelectedMonth, Model.MonthList)
When you submit your page the selected option will automatically get picked up.