New to Razor, c# and ASP and with refrence to the following. https://docs.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/?view=aspnetcore-2.1
Currently I'm able to arrange my rows from my model into a select view using the following code in my Pages code.
public SelectList Ratings { get; set; }
public async Task<IActionResult> OnGetAsync()
{
IQueryable<string> ratingQuery = from m in _context.Ratings
orderby m.MovieRating
select m.MovieRating;
Ratings = new SelectList(await ratingQuery.Distinct().ToListAsync());
return Page();
}
And within my HTML page reference that to produce a nice list of ratings to choose from.
<select asp-for="Movie.Rating" asp-items="Model.Ratings">
</select>
My issue is the options generated do not have a value other than that of the Movie.Rating field (ie GOOD, BAD, UGLY), everything works ok but when I inset into the DB I would like to inset the "ID" and not the "MovieRating"
I would like to have the following html created when the page is generated. Where the ID field from within the Table is the Value and the "MovieRating" is the Text.
<select asp-for="Movie.Rating" asp-items="Model.Ratings">
<option value="1">Good</option>
<option value="2">Bad</option>
<option value="3">Ugly</option>
</select>
In order to do this I know I need to select more than the "MovieRating" field within the select statement. So I can change this to also select the ID. However it will just spit out a combined string into the option field and not produce a value field.
Is this the correct method to achieve what I want to do. I can find a few examples online of how to achieve this another way but I do not want to delve into MVC just yet.
Your current LINQ query is SELECT ing a single column, MovieRating
and you are using the result of executing that query, which is a list of strings, to build the SelectList
object. Your select tag helper is using this SelectList
object which has only the MovieRating string values as the underlying items.
Assuming your Ratings
class has an Id
property( int
type) and MovieRating
property( string
type), you may create a SelectListItem
in the projection part of your LINQ expression.
List<SelectListItem> ratingItems = _context.Ratings
.Select(a=>new SelectListItem
{
Value=a.Id.ToString(),
Text = a.MovieRating
}).ToList();
Ratings = ratingItems;
return Page();
Here the ratingItems
is a list of SelectListItem
objects. So change your Ratings
properties type to a collection of SelectListItem
objects.
public List<SelectListItem> Ratings { get; set; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.