0

I'm trying to make app where I can manage clients. All my clients has his own client that I manage it. So I made database with two tables tboClienti for my clients and tboSottoClienti for my "under clients".

This is the structure of tables :

Structure of table Clients - tboClienti and structure of table Under Clients - tboSottoClienti.

I'm working on CRUD operations for my "under clients", and I wanted to make drop down list where I can select my client and insert info (name, surname, company, phone) for my under client.

This is how I imagine it.

I made a controller model and view for my under client, but I don't know how to make list in my View Razor Page.

This is controller :

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);
    }
}

This is the model class:

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; }
}

I don't know how to get the data from the table tboClienti to insert it into a list. So in that way I can select the Client for my under client.

And this is the view:

<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> 

I insert my connection string into appsettings.json, and I add it to ConfigureServices();.

And this is the class for the database context :

 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; }
}

Any suggestion how to get data from database and insert it to list?

Thanks in advance!

2 Answers 2

0

In ASP.NET Core MVC, your HTML code for dropdown list looks like this

 <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>

and in C# Controller

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

Original Answer : https://stackoverflow.com/a/55843644/3559462

For more detailed step by step procedure take a look at this link : https://www.c-sharpcorner.com/article/binding-dropdown-list-with-database-in-asp-net-core-mvc/

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I tried but the list is empty. I'm not sure that the paremeters are correct. I update my question
0

Debug your code and be sure your ViewData["lstClieti"] actually exist value.

Be sure if your View name is CreareLista or not.If the View name is CreareSottoCliente. Change like below:

//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();
}

The whole demo:

1.Model:

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.View name should be CreareSottoCliente.cshtml.

3.Controller:

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"
}

Result: enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.