In previous we seen how CRUD operations are performed in ASP.NET MVC using Dapper ORM.
Now today we'll see how to get a collection of records to View using ViewBag.
Display the collection of records in View is done by various way.
I'll show you how to do it using ViewBag.
I've already shown you how to install Dapper and give connection to database. If you are not aware for that than kindly view previous post.
Now I'll continue with creating model. I have a table name District_Master which contains District and it's code.
Model: (District.cs)
using System;using System.Collections.Generic;using System.Linq;using System.ComponentModel.DataAnnotations;using System.Web; using Dapper;using System.ComponentModel.DataAnnotations.Schema;namespace GetData.Models { [Dapper.Table("District_Matser")]private string _districtcode;public class District { private string _district;get { return _district; }[Display(Name="District")] public string DISTRICT {public string DISTRICTCODEset { _district = value; } } [Display(Name = "DistrictCode")] {}get { return _districtcode; } set { _districtcode = value; } }}
Now we have created a model that will get and set value to database for district_master.
But how would it perform dml or ddl operations?
So we'll create new model and let us call it as MainModel which would contain helper methods.
This method we'll access through controller and get the records to View.
MainModel.cs
using System;using System.Collections.Generic;using System.Linq;using System.ComponentModel.DataAnnotations;using System.Web; using Dapper;using System.ComponentModel.DataAnnotations.Schema;using System.Data; using System.Data.OracleClient; using System.Configuration;OracleConnection con = new OracleConnection(ConfigurationManager.ConnectionStrings["dbOraConn"].ConnectionString);namespace GetData.Models { public class MainModel {public IEnumerabledistrictdata() { string query = "select district,districtcode from district_master";if (con.State == ConnectionState.Closed) {var records = con.Querycon.Open(); }(query); return records; }}}
Controller:
Now create ActionResult method that will access the data and pass the data to view using ViewBag.
using System;using System.Collections.Generic;using System.Linq;using System.Web.Mvc;using System.Web;using Dapper;using GetRainData.Models;public class DefaultController : Controllernamespace GetData.Controllers { {public ActionResult Index()// GET: Default {var district = mm.districtdata().ToList();MainModel mm = new MainModel();}ViewBag.ddldistrict = district; return View(); }}
View:
Now data is passed to view. So after passing the data we've to cast the viewbag to it's datatype. I've casted to ICollection<T>. And for using models in view we have to import namespace using WebApplication.Models;
Just see now how it is being done.
Now run the application and see the output.