locked
how can I list the record in a partial view using entity frame work core dbcontext RRS feed

  • Question

  • User-1355965324 posted

    I am using ado.net connection in my application. But I am trying to list the Customer record  in my partial view  customersearch using entityframework core. So Please can you  help me with the suggested code how can I list the customer code and customer name  into the partial view file CustomerSearch using entityframework dbcontext . I am trying to list the customer code and name to be listed when they  click the button  in Sales view  file. 


    My Appsetting.json file 

    {
      "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "ConnectionSetting": {
        "ConnectionString": "Data Source=MOD-SQL\\SQLEXPRESS;Initial Catalog=MyDatabase; user id=sa; password=sa;"
        
      }
    }

    My Startup file

    namespace MyApp.GO.UI
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddDbContextPool<AttendanceDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));
                services.AddSession(options =>
                {
                    options.IdleTimeout = TimeSpan.FromHours(5);
                });
                services.AddMvc();
                services.Configure<ConnectionSetting>(Configuration.GetSection("ConnectionSetting"));
                services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
                services.AddOptions();
            }

    The DbContext file

    namespace MyApp.GO.UI.DBContext
    {
        public class AttendanceDbContext : DbContext
        {
            public AttendanceDbContext(DbContextOptions<AttendanceDbContext> options)
                : base(options)
            {
               
            }
            public DbSet<CustomerModel> Customer { get; set; }
                 
        }
    }
    

    my model class

     
    namespace MyApp.GO.UI.Models
    {
        public class CustomerModel
        {
            public string CustomerCode { get; set; }
            public string CustomerName { get; set; }
    
    
        }
    }
    

    Main view file Sales.chtml

     
    <div class="col-sm-3">
                            <input type="text" class="form-control" asp-for="CustomerCode" id="lblCustomer">
                            <button type="button" class="btn btn-primary form-control" onclick="ShowCustomerSearch()">Search</button>
                        </div>
    <script type="text/javascript">
    function ShowCustomerSearch() {
            debugger;
            var url = "/Sales/SearchCustomer";
    
            $("#CustomerSearchDiv").load(url, function () {
                $("#CustomerSearchModal").modal("show");
            })
        }
    </script>

    Partial view Customer cshtml

    Partial View File
    @model CustomerModel
    <div class="table-responsive">
        <Table id="CustomerSearch" class="table table-bordered table-striped" style="width:100%;font-size:90%">
            <thead class="thead-light">
                <tr>
                    <th> Customer Code </th>
                    <th> Customer Name </th>
                </tr>
    
            </thead>
            <tbody>
                <tr>
                    <td>CustomerCode</td>
                    <td>CustomerName</td>
                </tr>
            </tbody>
        </Table>
        Customer Search from Cameo Customer
    </div>

    In Sales Contoller

     public IActionResult SearchCustomer()
            {
                List<CustomerModel> CustomerList = new List<CustomerModel>();  // I am trying to list the customer from customer table 
                return PartialView("CustomerSearch");
            }

    Friday, July 26, 2019 11:54 AM

Answers

  • User475983607 posted

    Is it possible to add the connectionsetting  variable into the constructor.

    The connection string an option in the startup configuration.  I recommend that you use standard patterns that are illustrated in the ASP.NET Core and EF Core fundamentals documentation rather than making up your own pattern.

    https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro?view=aspnetcore-2.2

    Your startup will look similar to the following.

    var connection = @"Server=MyDb;Database=AdventureWorksLT2008R2;Trusted_Connection=True;";
    services.AddDbContext<AdventureWorksLT2008R2Context>(options => options.UseSqlServer(connection));

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, July 28, 2019 1:29 PM
  • User711641945 posted

    Hi polachan,

    As mgebhard said,If you want to use EF core you could refer to the link and focus on here. There is my Startup.cs and appsetting.json as follow:

    1.Startup.cs:

    public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.Configure<CookiePolicyOptions>(options =>
                {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    options.CheckConsentNeeded = context => true;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
                services.AddDbContext<AttendanceDbContext>(options =>
                        options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));          
            }
    }

    2.appsetting.json:

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

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 29, 2019 2:27 AM

All replies

  • User-474980206 posted

    your controller should get a dbcontext by DI

    your search action should pass the list to the partial view

    your partial view should render this list and return html

    your ajax call should add the response html to the dom

    Saturday, July 27, 2019 9:49 PM
  • User711641945 posted

    Hi polachan,

    Here is a working demo like below,be attention to something that mark it with green:

    1.Model:

    public class CustomerModel
        {
            [Key]
            public string CustomerCode { get; set; }
            public string CustomerName { get; set; }
        }

    2.View(Index.cshtml):

    <div class="col-sm-3">
        <input type="text" class="form-control" id="lblCustomer">
        <button type="button" class="btn btn-primary form-control" onclick="ShowCustomerSearch()">Search</button>
    </div>
    <div id="CustomerSearchDiv">
        <div id="CustomerSearchModal"></div>
    </div>
    @section Scripts{ 
    <script type="text/javascript">
        function ShowCustomerSearch() {
            var searchString = $("#lblCustomer").val();
            var url = "/CustomerModels/SearchCustomer";
            $("#CustomerSearchDiv").load(url, { searchString }, function (res) {            
                console.log(res);
                $("#CustomerSearchModal").modal("show");
            })
        }
    </script>
    }
    

    3.Partial VIew(_SearchCustomer.cshtml):

    @model CustomerModel
        <table class="table">
            <thead>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.CustomerCode)
                    </th>
                    <th> @Html.DisplayNameFor(model => model.CustomerName)</th>
                </tr>
            </thead>
            <tbody>
                    <tr>
                        <td>
                            @Html.DisplayFor(model => model.CustomerCode)
                        </td>
                        <td>
                            @Html.DisplayFor(model => model.CustomerName)
                        </td>
                    </tr>
    
            </tbody>
        </table>
    

    4.controller(CustomerModelsController):

    public class CustomerModelsController : Controller
        {
            private readonly AttendanceDbContext _context;
    
            public CustomerModelsController(AttendanceDbContext context)
            {
                _context = context;
            }
            public IActionResult SearchCustomer(string searchString)
            {
                // I am trying to list the customer from customer table
                var model = _context.CustomerModel
                    .Where(c=>c.CustomerCode==searchString).FirstOrDefault();
                return PartialView("_SearchCustomer", model);
            }
            // GET: CustomerModels
            public async Task<IActionResult> Index()
            {
                return View();
            }
    }

    Best Regards,

    Rena

    Sunday, July 28, 2019 5:53 AM
  • User-1355965324 posted

    Rena Many Thanks. I have applied your code into the system . Now I am calling the constructor properly but now  the view file is not loaded. But when I comment the following highlighted lines it will work.  I am calling the constructor two times one for dbcontext another for connection setting . Is it possible to add the connectionsetting  variable into the constructor. Pleasse can you advise me .please can you let me how could be added the connectionsetting variable with constructer. Please help

    public class CustomerModelsController : Controller
        {
            private readonly AttendanceDbContext _context;
    
            public CustomerModelsController(AttendanceDbContext context)
            {
                _context = context;
            }
    
             public CustomerModelsController(IOptions<ConnectionSetting> connectionSettings)
            {
                this.connectionSettings = connectionSettings;             
                            
            }
    
    
            public IActionResult SearchCustomer(string searchString)
            {
                // I am trying to list the customer from customer table
                var model = _context.CustomerModel
                    .Where(c=>c.CustomerCode==searchString).FirstOrDefault();
                return PartialView("_SearchCustomer", model);
            }
            // GET: CustomerModels
            public async Task<IActionResult> Index()
            {
                return View();
            }
    }

    Sunday, July 28, 2019 7:56 AM
  • User475983607 posted

    Is it possible to add the connectionsetting  variable into the constructor.

    The connection string an option in the startup configuration.  I recommend that you use standard patterns that are illustrated in the ASP.NET Core and EF Core fundamentals documentation rather than making up your own pattern.

    https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro?view=aspnetcore-2.2

    Your startup will look similar to the following.

    var connection = @"Server=MyDb;Database=AdventureWorksLT2008R2;Trusted_Connection=True;";
    services.AddDbContext<AdventureWorksLT2008R2Context>(options => options.UseSqlServer(connection));

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, July 28, 2019 1:29 PM
  • User-2054057000 posted

    Your configureservices() method needs to be updated so that you can use the connection string from your appsettings.json file. There is a reference tutorial for this check here.

    Sunday, July 28, 2019 2:26 PM
  • User711641945 posted

    Hi polachan,

    As mgebhard said,If you want to use EF core you could refer to the link and focus on here. There is my Startup.cs and appsetting.json as follow:

    1.Startup.cs:

    public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.Configure<CookiePolicyOptions>(options =>
                {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    options.CheckConsentNeeded = context => true;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
                services.AddDbContext<AttendanceDbContext>(options =>
                        options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));          
            }
    }

    2.appsetting.json:

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

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 29, 2019 2:27 AM
  • User-1355965324 posted

    Many Thanks Rena

    Monday, July 29, 2019 4:14 AM