问题描述
在为 chinook 数据库创建曲目时,我设置了一个 SelectList 来选择专辑。按照 Microsoft docs 说明,出于某种原因(由于我仍在努力学习,我看不到),它不喜欢我在剃须刀页面上看到的内容。演练代码如下。
实体:
public class Album
{
public int AlbumId { get; set; }
public string Title { get; set; }
public int ArtistId { get; set; }
//related entities
public virtual ICollection<Track> Tracks { get; set; }
public virtual Artist Artist { get; set; }
}
public class Track
{
public int TrackId { get; set; }
public string Name { get; set; }
public int AlbumId { get; set; }
public string Composer { get; set; }
public int Milliseconds { get; set; }
public int Bytes { get; set; }
public double UnitPrice { get; set; }
public int MediaTypeId { get; set; }
public int GenreId { get; set; }
//related entities
public virtual Album Album { get; set; }
}
为 SelectedList 创建模型:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using UWS.Project;
namespace Project.Pages.Albums
{
public class AlbumPageModel : PageModel
{
public SelectList AlbumNameSL { get; set; }
public void PopulateAlbumsDropDownList(Chinook db,object selectedAlbum = null)
{
var albumsQuery = from a in db.Albums
orderby a.Title // Sort by name.
select a;
AlbumNameSL = new SelectList(albumsQuery,"AlbumId","Title",selectedAlbum);
}
}
}
现在我的模型用于创建轨道:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using UWS.Project;
namespace Project.Pages.Albums
{
public class TrackCreateModel : AlbumPageModel
{
private Chinook db;
public TrackCreateModel(Chinook injectedContext)
{
db = injectedContext;
}
public IActionResult OnGet(int? id)
{
PopulateAlbumsDropDownList(db);
return Page();
}
[BindProperty]
public Track Track { get; set; }
public async Task<IActionResult> OnPostAsync()
{
var emptyTrack = new Track();
if (await TryUpdateModelAsync<Track>(
emptyTrack,"track",// Prefix for form value.
s => s.AlbumId,s => s.Name,s => s.Composer,s => s.Milliseconds,s => s.Bytes,s
=> s.MediaTypeId,s => s.GenreId,s => s.UnitPrice))
{
db.Tracks.Add(emptyTrack);
await db.SaveChangesAsync();
return RedirectToPage("./Index");
}
// Select AlbumId if TryUpdateModelAsync fails.
PopulateAlbumsDropDownList(db,emptyTrack.AlbumId);
return Page();
}
}
}
尝试在我看来实现 SelectList:
作为新手,我一辈子都看不到这个问题。我在此处查看了 SelectedList 的先前问题,但没有一个与我的问题有关。任何帮助将不胜感激。
解决方法
不要在 ipw.FloatText(value=list_of_values[val] for val in list_of_values,
的 PopulateAlbumsDropDownList
方法中输入 selectedValue
目前您要么将其留空,要么提供一个 id,但这无论如何都行不通