【问题标题】:How to populate list in ASP.NET Entity Framework from database如何从数据库中填充 ASP.NET 实体框架中的列表
【发布时间】:2020-06-17 12:17:49
【问题描述】:

我正在尝试制作可以管理客户的应用程序。我所有的客户都有他自己的客户,由我管理。所以我为我的客户创建了两个表tboClientitboSottoClienti 为我的“下客户”创建了数据库。

这是表格的结构:

Structure of table Clients - tboClientistructure of table Under Clients - tboSottoClienti

我正在为我的“下属客户”进行 CRUD 操作,我想制作下拉列表,我可以在其中选择我的客户并为我的下属客户插入信息(姓名、姓氏、公司、电话)。

This is how I imagine it.

我为我的下客户端制作了一个控制器模型和视图,但我不知道如何在我的 View Razor 页面中制作列表。

这是控制器:

public class SottoClientiController : Controller
{
    private readonly AppDbContext _db;

    public SottoClientiController(AppDbContext db)
    {
        _db = db;
    }

    public IActionResult Index()
    {
        var datiSottoClienti = _db.tboSottoClienti.ToList();
        return View(datiSottoClienti);
    }


    public IActionResult CreareLista()
    {
        ViewData["lstClieti"] = new SelectList(_db.tboClienti, "Id", "Nome_azienda");
        return View();
    }
    public IActionResult CreareSottoCliente()
    {
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> CreareSottoCliente(SottoCliente sottoCliente) 
    {
        if (ModelState.IsValid)
        {
            _db.Add(sottoCliente);
            await _db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        return View(sottoCliente);
    }
}

这是模型类:

public class SottoCliente
{
    [Key]
    public int Id { get; set; }

    [Required(ErrorMessage = "Inserisci il nome di proprietario dell'azienda")]
    [Display(Name = "Nome")]
    public string Nome { get; set; }

    [Required(ErrorMessage = "Inserisci il cognome di proprietario dell'azienda")]
    [Display(Name = "Cognome")]
    public string Cognome { get; set; }

    [Display(Name = "Azienda")]
    public string Azienda { get; set; }

    [Required(ErrorMessage = "Inserisci il numero di telefono dell'azienda")]
    [DataType(DataType.PhoneNumber)]
    [Display(Name = "Telefono")]
    [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
       ErrorMessage = "Numero non valido")]
    public string Cellulare { get; set; }
}

我不知道如何从表tboClienti 中获取数据以将其插入列表。所以这样我就可以为我的下属客户选择客户。

这是视图:

<h4>Under Client</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="CreareSottoCliente">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>

           <div class="form-group">
            <label asp-for="Azienda" class="control-label"></label>
            <select asp-for="Azienda" class="form-control" asp-items="@ViewBag.lstClieti"></select>
            <span asp-validation-for="Azienda" class="text-danger"></span>
        </div>

            <div class="form-group">
                <label asp-for="Id" class="control-label"></label>
                <input asp-for="Id" class="form-control" />
                <span asp-validation-for="Id" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Nome" class="control-label"></label>
                <input asp-for="Nome" class="form-control" />
                <span asp-validation-for="Nome" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Cognome" class="control-label"></label>
                <input asp-for="Cognome" class="form-control" />
                <span asp-validation-for="Cognome" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Azienda" class="control-label"></label>
                <input asp-for="Azienda" class="form-control" />
                <span asp-validation-for="Azienda" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Cellulare" class="control-label"></label>
                <input asp-for="Cellulare" class="form-control" />
                <span asp-validation-for="Cellulare" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div> 

我将连接字符串插入appsettings.json,然后将其添加到ConfigureServices();

这是数据库上下文的类:

 public class AppDbContext: DbContext
 {
        public AppDbContext(DbContextOptions<AppDbContext> options): base (options)
        {
        }

        public DbSet<Tecnico> tboTecnici { get; set; }
        public DbSet<Cliente> tboClienti { get; set; }
        public DbSet<SottoCliente> tboSottoClienti { get; set; }
}

对如何从数据库中获取数据并将其插入列表有什么建议吗?

提前致谢!

【问题讨论】:

    标签: c# asp.net asp.net-mvc entity-framework asp.net-core


    【解决方案1】:

    在 ASP.NET Core MVC 中,下拉列表的 HTML 代码如下所示

     <div class="form-group">
            <label asp-for="NewsTypeId" class="control-label"></label>
            <select asp-for="NewsTypeId" class="form-control" asp-items="@ViewBag.NewsTypeId"></select>
            <span asp-validation-for="NewsTypeId" class="text-danger"></span>
        </div>
    

    在 C# 控制器中

    public IActionResult Create()
    {
        ViewData["NewsTypeId"] = new SelectList(_context.TypeOfNews, "TypeId", "TypeName");
        return View();
    }
    

    原答案:https://stackoverflow.com/a/55843644/3559462

    有关更详细的分步程序,请查看此链接:https://www.c-sharpcorner.com/article/binding-dropdown-list-with-database-in-asp-net-core-mvc/

    【讨论】:

    • 谢谢!我试过了,但列表是空的。我不确定参数是否正确。我更新了我的问题
    【解决方案2】:

    调试您的代码并确保您的 ViewData["lstClieti"] 确实存在值。

    确定您的视图名称是否为CreareLista。如果视图名称为CreareSottoCliente。 如下更改:

    //public IActionResult CreareLista()
    //{
    //    ViewData["lstClieti"] = new SelectList(_db.tboClienti, "Id", "Nome_azienda");
    //    return View();
    //}
    public IActionResult CreareSottoCliente()
    {
        ViewData["lstClieti"] = new SelectList(_db.tboClienti, "Id", "Nome_azienda");
        return View();
    }
    

    整个演示:

    1.型号:

    public class SottoCliente
    {
        [Key]
        public int Id { get; set; }
    
        [Required(ErrorMessage = "Inserisci il nome di proprietario dell'azienda")]
        [Display(Name = "Nome")]
        public string Nome { get; set; }
    
        [Required(ErrorMessage = "Inserisci il cognome di proprietario dell'azienda")]
        [Display(Name = "Cognome")]
        public string Cognome { get; set; }
    
        [Display(Name = "Azienda")]
        public string Azienda { get; set; }
    
        [Required(ErrorMessage = "Inserisci il numero di telefono dell'azienda")]
        [DataType(DataType.PhoneNumber)]
        [Display(Name = "Telefono")]
        [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
           ErrorMessage = "Numero non valido")]
        public string Cellulare { get; set; }
    }
    public class Cliente
    {
        public int Id { get; set; }
        public string Nome_azienda { get; set; }
    }
    

    2.视图名称应为CreareSottoCliente.cshtml

    3.控制器:

    public class SottoClientiController : Controller
    {
        private readonly MvcProj3_1Context _db;
        public SottoClientiController(MvcProj3_1Context db)
        {
            _db = db;
        }
    
        public IActionResult Index()
        {
            var datiSottoClienti = _db.tboSottoClienti.ToList();
            return View(datiSottoClienti);
        }
        //SottoClienti/CreareSottoCliente
        public IActionResult CreareSottoCliente()
        {
            ViewData["lstClieti"] = new SelectList(_db.tboClienti, "Id", "Nome_azienda");
            return View();
        }
    
        [HttpPost]
        public async Task<IActionResult> CreareSottoCliente(SottoCliente sottoCliente)
        {
            if (ModelState.IsValid)
            {
                _db.Add(sottoCliente);
                await _db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
    
            return View(sottoCliente);
        }
    }
    

    4.DbContext:

    public class MvcProj3_1Context : DbContext
    {
        public MvcProj3_1Context (DbContextOptions<MvcProj3_1Context> options)
            : base(options)
        {
        }       
        public DbSet<Tecnico> tboTecnici { get; set; }
        public DbSet<Cliente> tboClienti { get; set; }
        public DbSet<SottoCliente> tboSottoClienti { get; set; }
    }
    

    5.Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    
        services.AddDbContext<MvcProj3_1Context>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("MvcProj3_1Context")));
    }
    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseHttpsRedirection();
        app.UseStaticFiles();
    
        app.UseRouting();
    
        app.UseAuthorization();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
    

    6.appSettings.json:

    "ConnectionStrings": {
       "MvcProj3_1Context": "Server=(localdb)\\mssqllocaldb;Database=DatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true"
    }
    

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-25
      • 1970-01-01
      相关资源
      最近更新 更多