Executing a stored procedure in mvc4 - sql

I want to execute a insert query in mvc4 on action button,
i have the below action method in my controller
[HttpPost]
public ActionResult Index(QuestionBank model)
{
try
{
using (var db = new AdminContext())
{
db.Questions.Add(model);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I have related model
public class QuestionBank
{
[Key]
////[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public string question { get; set; }
}
As we do in simple asp.net application i want to execute that stored procedure on action button.
I don't know whether my approach is right, but please guide me on this.

I'm assuming that you wan't to use the stored procedure approach to execute inserting a question into the database.
[HttpPost]
public ActionResult Index(QuestionBank model)
{
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("[dbo].[sp_addQuestion]", conn) { CommandType = CommandType.StoredProcedure, CommandTimeout = 0 };
cmd.Parameters.Add(new SqlParameter("question", model.question) { SqlDbType = SqlDbType.Structured });
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
cmd.ExecuteNonQuery();
}
//using (var db = new AdminContext())
//{
// db.Questions.Add(model);
// db.SaveChanges();
//}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Here's the corresponding stored procedure
ALTER PROCEDURE [dbo].[sp_addQuestion]
#question nvarchar(255)
AS
BEGIN
INSERT INTO [dbo].[QuestionBank] (Question)
VALUES (#question)
RETURN ##ERROR;
END

Related

How is raw SQL run against an Entity Framework Core context?

I have used Entity Framework for a long time, but have an edge case where I need to use SQL. I was wondering if I could use my existing Entity Framework Core context for this or not. Here is what I have currently, but the queryResults variable contains a "-1" value, instead of a list of Students, after running it:
string tableName = "Students";
var queryResults = db.Database.ExecuteSqlRaw(#"SELECT * FROM {0}", tableName);
Any ideas?
Entity Framework Core 3.1
.NET Core 3.1
Linq-to-SQL
It is possible; I just had to do this for a pet project.
You need to reference the Microsoft.EntityFrameworkCore.Relational NuGet.
ConsoleApp Example:
Program.cs
using System.Collections.Generic;
namespace EfDirectSql
{
class Program
{
/*
* written: VS2019 .Net Core 3.1 Console App
*
* used nugets:
*
* Microsoft.EntityFrameworkCore.SqlServer 3.1.0
* Microsoft.EntityFrameworkCore.Relational 3.1.0
*
*/
static void Main(string[] args)
{
// attention: supply your database server name
ApplicationContext context = new ApplicationContext("?YOURSERVER?", "Master");
// note: leveraging included extension methods for the dbContext class.
object scalarResult = context.ExecuteScalar("SELECT COUNT(1) FROM Master.dbo.SysObjects");
object nonQueryResult = context.ExecuteNonQuery("SELECT * FROM Master.dbo.SysObjects"); // likely your -1
IEnumerable<SysObject> readerResult = context.ExecuteReader<SysObject>("SELECT * FROM Master.dbo.SysObjects");
}
}
}
ApplicationContext.cs
using Microsoft.EntityFrameworkCore;
namespace EfDirectSql
{
public class ApplicationContext
: DbContext
{
public ApplicationContext(string serverName, string catalogName)
{
this.ServerName = serverName;
this.CatalogName = catalogName;
}
public readonly string ServerName;
public readonly string CatalogName;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer($"Data Source={this.ServerName};Initial Catalog={this.CatalogName};Integrated Security=true;");
base.OnConfiguring(optionsBuilder);
}
}
}
DbContextExtensions.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
namespace EfDirectSql
{
public static class DbContextExtensions
{
public static object ExecuteScalar
(
this DbContext context,
string sql
)
{
IDbConnection connection = context.Database.GetDbConnection();
IDbCommand command = connection.CreateCommand();
object result = null;
try
{
connection.Open();
command.CommandText = sql;
command.CommandType = CommandType.Text;
result = command.ExecuteScalar();
}
finally
{
connection.Close();
}
return result;
}
public static int ExecuteNonQuery
(
this DbContext context,
string sql
)
{
IDbConnection connection = context.Database.GetDbConnection();
IDbCommand command = connection.CreateCommand();
int result;
try
{
connection.Open();
command.CommandText = sql;
command.CommandType = CommandType.Text;
result = command.ExecuteNonQuery();
// likely the -1
}
finally
{
connection.Close();
}
return result;
}
public static IEnumerable<TType> ExecuteReader<TType>
(
this DbContext context,
string sql
)
where TType : class, new()
{
IDbConnection connection = context.Database.GetDbConnection();
IDbCommand command = connection.CreateCommand();
IEnumerable<TType> result = new List<TType>();
try
{
connection.Open();
command.CommandText = sql;
command.CommandType = CommandType.Text;
IDataReader reader = command.ExecuteReader(CommandBehavior.Default);
result = Convert<TType>(reader);
}
finally
{
connection.Close();
}
return result;
}
private static IEnumerable<TType> Convert<TType>(IDataReader reader)
where TType : class, new()
{
List<PropertyInfo> properties = typeof(TType)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanWrite)
.ToList();
IList<TType> instances = new List<TType>();
while (reader.Read())
{
TType instance = new TType();
properties
.ForEach
(p =>
// for the purposes of the example, this works - could be outliers.
p.SetValue(instance, reader[p.Name] == DBNull.Value ? null : reader[p.Name])
);
instances.Add(instance);
}
return instances;
}
}
}
SysObject.cs
namespace EfDirectSql
{
// shortened represenation of the MS-SQL sysobject table
public class SysObject
{
public string name { get; set; }
public int id { get; set; }
public string xtype { get; set; }
public int uid { get; set; }
public int info { get; set; }
public int status { get; set; }
// the rest are not needed for a demo.
}
}
"I was wondering if I could use my existing Entity Framework Core context for this or not":
Yes you can use your existing databaseContext but you have to execute that query on your dbContext Entity see the example below:
var sqlCommand = $"SELECT * FROM Students";
var executeSQL = await _context.Students.FromSqlRaw(sqlCommand).ToListAsync();
return Ok(executeSQL);
Output:
Note: As you can see I am executing sqlCommand on Students dbContext this is valid. But using DbContext you cannot pass the
table name dynamically. You must need to define it explicitly.
Hope above steps guided you accordingly, You can have a look on official document for more details here
Update Using Ado.Net Connection:
using (var connection = _context.Database.GetDbConnection())
{
connection.Open();
var tableName = "Students";
List<Student> _listStudent = new List<Student>();
var command = connection.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = string.Format("SELECT * FROM [{0}];", tableName);
SqlDataReader reader = (SqlDataReader)command.ExecuteReader();
while (reader.Read())
{
var student = new Student(); // You have to bind dynamic property here based on your table entities
student.FirstName = reader["FirstName"].ToString(); // Remember Type Casting is required here it has to be according to database column data type
student.LastName = reader["LastName"].ToString();
_listStudent.Add(student);
}
reader.Close();
command.Dispose();
connection.Close();
}

C# foreach loop skipping some values during iteration

I have a multi-select control whereby I need to commit all items selected to SQL Server table. When I submit the form only 1 item is getting committed even though when i inspect using Step Debugger all the selected values are indeed populated in variable employeees4 (attached image). i have observed that only the first item in the selection is getting committed. Any help on what i could possibly be missing?
Please note that i have used slightly different variable name in attached image has i.e year instead of employeees4, but the code is the same .
I am getting selected items as below :
[HttpPost]
public ActionResult NewOverTimeRequest(FormCollection formcollection)
{
Models.Employee.OverTimeRequest request = new Models.Employee.OverTimeRequest();
try
{
var batch = new OvertimeBatch();
request.employees = GetEmployees();
request.EmployeeNumber = new string[] { Convert.ToString(formcollection["EmployeeNumber"]) };
var employeees1= request.EmployeeNumber.Split(',');
string[] employeees2 = employeees.SingleOrDefault().ToArray();
string employeees3 = Helpers.ConvertStringArrayToString( employeees2);
string[] employeees4 =employeees3.Split(new char[] { ',' });
if (ModelState.IsValid)
{
foreach ( string emp in employeees4)
{
using (SqlConnection conn = new SqlConnection(Helpers.DatabaseConnect))
{
SqlCommand cmd = new SqlCommand("SubmitOverTime", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpNum", emp);
cmd.Parameters.AddWithValue("#DateDone", DateTime.Now);
conn.Open();
cmd.ExecuteNonQuery();
}
}
return RedirectToAction("OverTime");
}
catch (Exception ex)
{
ViewBag.ErrorMessage = ex.Message;
return View(request);
}
return RedirectToAction("OverTime");
}
}
Model :
[Required]
[Display(Name = "Employee ")]
public string[] EmployeeNumber { get; set; }
public Employee Employee { get; set; }
public String DisplayName { get; set; }
public IEnumerable<SelectListItem> employees { get; set; }
Try changing you If condition to below.
if (ModelState.IsValid)
{
using(SqlConnection conn = New SqlConnection(Helpers.DatabaseConnect))
{
conn.Open();
SqlCommand cmd = New SqlCommand("SubmitOverTime", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#EmpNum", SqlDbType.varchar(max));
cmd.Parameters.Add("#DateDone", SqlDbType.DateTime);
foreach(String emp In employeees4)
{
cmd.Parameters["#FixtureId"].Value=emp;
cmd.Parameters["#FixtureId"].Value= DateTime.Now;
cmd.ExecuteNonQuery();
}
}
return RedirectToAction("OverTime");
}

ASP.Net Core - setting and getting session variables

I have an application using ASP.NET Core, Angular 5 And ADO.NET
It worked fine until I decided to change the code to set a session variable with a database connection string gotten from my appssettings.json file.
I am using this as a reference: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2
However, when I try to set the session variable, I get a Null object reference in my SetSessionVariable() method.
Error is:
An error occurred while starting the application.
NullReferenceException: Object reference not set to an instance of an
object. Angular5NetcoreAdo.Startup.SetSessionVariable() in Startup.cs,
line 82
My code is:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Angular5NetcoreAdo.Models;
// Added these.
using Microsoft.AspNetCore.Http;
using System;
namespace Angular5NetcoreAdo
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// Added this.
public HttpContext HttpContext { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// In production, the Angular files will be served from this directory.
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
services.AddScoped<EmployeeDataAccessLayer>();
// Added this.
services.AddSession(options =>
{
options.Cookie.Name = ".ConnectionString";
});
// Added this.
SetSessionVariable();
}
// Added this.
public void SetSessionVariable()
{
HttpContext.Session.SetString("ConnectionString", Convert.ToString(Configuration.GetConnectionString("DBAngular5NetcoreAdoDatabase")));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseSpaStaticFiles();
// Added this.
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}
---- Per a suggestion below, I am including that code here:
// Middleware extension method.
using Microsoft.AspNetCore.Builder;
namespace Angular5NetcoreAdo
{
public static class RequestConnectionMiddlewareExtensions
{
public static IApplicationBuilder UseRequestConnection(this
IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestConnectionMiddleware>();
}
}
}
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using System;
using Microsoft.Extensions.Configuration;
namespace Angular5NetcoreAdo
{
public class RequestConnectionMiddleware
{
public IConfiguration Configuration { get; }
public HttpContext HttpContext { get; }
private readonly RequestDelegate _next;
public RequestConnectionMiddleware(RequestDelegate next,
IConfiguration configuration)
{
_next = next;
Configuration = configuration;
}
public async Task InvokeAsync(HttpContext context)
{
// Set the session variable with the database connection string from appsettings.json.
HttpContext.Session.SetString("ConnectionString", Convert.ToString(Configuration.GetConnectionString("DBAngular5NetcoreAdoDatabase")));
await _next(context);
}
}
}
Now in the Startup.cs, I call the new middleware message method after the app.UseSession();
app.UseSession();
// Call the middlware now to set the session variable with the database
// connection string from appsettings.json.
app.UseRequestConnection();
------------------ Added now as a new error refers to this class.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Http;
namespace Angular5NetcoreAdo.Models
{
public class EmployeeDataAccessLayer
{
public HttpContext HttpContext { get; }
public string connectionString;
public EmployeeDataAccessLayer(HttpContext httpContext)
{
// Set the property.
HttpContext = httpContext;
// Get the connection string session variable.
connectionString = HttpContext.Session.GetString("ConnectionString");
}
public IEnumerable<Employee> GetAllEmployees()
{
try
{
List<Employee> lstemployee = new List<Employee>();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SelectEmployees", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee employee = new Employee();
employee.ID = Convert.ToInt32(rdr["EmployeeID"]);
employee.Name = rdr["Name"].ToString();
employee.Gender = rdr["Gender"].ToString();
employee.Department = rdr["Department"].ToString();
employee.City = rdr["City"].ToString();
lstemployee.Add(employee);
}
rdr.Close();
con.Close();
}
return lstemployee;
}
catch
{
throw;
}
}
public Employee GetEmployeeData(int id)
{
try
{
Employee employee = new Employee();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SelectEmployeeById", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpId", id);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
employee.ID = Convert.ToInt32(rdr["EmployeeID"]);
employee.Name = rdr["Name"].ToString();
employee.Gender = rdr["Gender"].ToString();
employee.Department = rdr["Department"].ToString();
employee.City = rdr["City"].ToString();
}
rdr.Close();
con.Close();
}
return employee;
}
catch
{
throw;
}
}
public int AddEmployee(Employee employee)
{
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("InsertEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Name", employee.Name);
cmd.Parameters.AddWithValue("#City", employee.City);
cmd.Parameters.AddWithValue("#Department", employee.Department);
cmd.Parameters.AddWithValue("#Gender", employee.Gender);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
return 1;
}
catch
{
throw;
}
}
public int UpdateEmployee(Employee employee)
{
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("UpdateEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpId", employee.ID);
cmd.Parameters.AddWithValue("#Name", employee.Name);
cmd.Parameters.AddWithValue("#City", employee.City);
cmd.Parameters.AddWithValue("#Department", employee.Department);
cmd.Parameters.AddWithValue("#Gender", employee.Gender);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
return 1;
}
catch
{
throw;
}
}
public int DeleteEmployee(int id)
{
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("DeleteEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpId", id);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
return 1;
}
catch
{
throw;
}
}
}
}
Its because documentation says
HttpContext.Session can't be accessed before UseSession has been
called.
and you call it in ConfigurationServices method where HttpContext.Session does not exist yet.
So you will need create your own middleware and call it after UseSession() method in Configure method.

Not able to insert data into SQL Server 2014 using Asp.net MVC4

I am totally new in .net, I tried to follow following link tutorial
https://www.youtube.com/watch?v=WLD6DvLI35Y&list=PLx7nFxMa-ZcIz2VBKC8FyMjQNmlIvrAi9
but like second video, not adding data into database. I am not able to find bug.
I am using VS Express 2012, ASP.NET MVC4 and SQL Server 2014.
Here is my code:
Index.cshtml
#model MyApp.Models.StudentModel
#{
ViewBag.Title = "Index";
}
<h2>Hi #ViewBag.message</h2>
#using (Html.BeginForm("SaveDataStudent", "Student", new { #id = "Form" }, FormMethod.Post))
{
#Html.ValidationSummary();
#Html.AntiForgeryToken();`
#Html.LabelFor(m=>m.productname)
#Html.TextAreaFor(m=>m.productname)
#Html.ValidationMessageFor(m => m.productname)
#Html.LabelFor(m=>m.quantity)
#Html.TextAreaFor(m=>m.quantity)
#Html.ValidationMessageFor(m => m.quantity)
#Html.LabelFor(m=>m.price)
#Html.TextAreaFor(m=>m.price)
#Html.ValidationMessageFor(m => m.price)
<input type="submit" value ="Save" name ="Save" />
}
#section Scripts{
#Scripts.Render("~/bundles/jqueryval")
}
StudentCotroller
using MyApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MyApp.Controllers
{
public class StudentController : Controller
{
// GET: /Student/
protected CodeDB d = new CodeDB();
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveDataStudent(StudentModel f)
{
if (ModelState.IsValid)
{
d.Open();
int i = d.DataInsert("INSERT INTO tblproduct(productname,price,quantity)VALUES('" + f.productname + "','" + f.price + "','" + f.quantity + "')");
//here getting i=0
if (i > 0)
{
ModelState.AddModelError("Success", "Save Success");
}
else
{
ModelState.AddModelError("Error", "Save Error");
}
d.Close();
}
else
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
}
return View("Index");
}
}
}
CodeDB.cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Configuration;`
namespace MyApp.Models
{
public class CodeDB
{
protected SqlConnection con;`
public bool Open(string Connection = "DefaultConnection")
{
con = new SqlConnection(#WebConfigurationManager.ConnectionStrings[Connection].ToString());
try
{
bool b = true;
if (con.State.ToString() != "Open")
{
con.Open();
}
return b;
}
catch (SqlException ex)
{
return false;
}
}
//end Open Connection
//close connection
public bool Close()
{
try
{
con.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
public int ToInt(Object s)
{
try
{
return Int32.Parse(s.ToString());
}
catch
{
return 0;
}
}
//Insert Data
public int DataInsert(String sql)
{
int lastID = 0;
String query = sql + ";SELECT##Identity;";
try
{
if (con.State.ToString() == "Open")
{
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
lastID = this.ToInt(cmd.ExecuteScalar());
}
return this.ToInt(lastID);
}
catch
{
return 0;
}
}
}
}
}
Student.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;`
namespace MyApp.Models
{
public class StudentModel
{
[StringLength(5)]
[Required]
[Display(Name = "Name:")]
public string productname { get; set; }`
[StringLength(3,MinimumLength=2,ErrorMessage="Min 5 max 10")]
[Required]
[Display(Name = "Quantitys:")]
public string quantity { get; set; }
[Required(ErrorMessage = "Please enter price.")]
public string price { get; set; }
}
}
Web.config
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=DESKTOP-VC6FUTV\SQLEXPRESS;Initial Catalog=MVC4;Persist Security Info=True;User ID=sa;Password=root"
providerName="System.Data.SqlClient" />
</connectionStrings>
Where is my mistake ?
I haven't tested it but I think you need a space between SELECT and ##Identity here:
String query = sql + ";SELECT##Identity;";
I think you're getting the 0 from the catch block inside the DataInsert method.
Also, you're executing the query twice; remove cmd.ExecuteNonQuery();.
As a side remark, you might want to reconsider the way you're adding errors to the ModelState. I would remove the property name from this statement ModelState.AddModelError("Error", "Save Error"); since "Error" is not a property of your model (so make it ModelState.AddModelError(string.Empty, "Save Error");). You will need a validation summary in your view to display non-property errors (such as "Save Error").

How to Bind Model Class in MVC

I am retrieving records from store procedure, but it does not bind data into view.
Here is ModelContext class:
namespace MyTesting.Models
{
public class TvSerialDB
{
public static string constr = ConfigurationManager.ConnectionStrings["TvSerialContext"].ConnectionString;
SqlConnection con;
SqlCommand cmd;
public IEnumerable<TVSerialByGroup> tvserialgroupby(string serialname)
{
List<TVSerialByGroup> tvserials = new List<TVSerialByGroup>();
using (con = new SqlConnection(constr))
{
cmd = new SqlCommand("pSerialListGroupBySerialName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#SerialName", SqlDbType.VarChar, 100).Value = serialname;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
TVSerialByGroup tvs = new TVSerialByGroup();
tvs.Series_Name = sdr["Series_Name"].ToString();
tvs.Image_Url_Big = sdr["Image_Url_Big"].ToString();
tvs.Season_No = sdr["Season_No"].ToString();
tvs.TotalEpisode = sdr["TotalEpisode"].ToString();
}
}
return tvserials;
}
}
}
Here is ModelClass:
namespace MyTesting.Models
{
public class TVSerialByGroup
{
public string Series_Name { get; set; }
public string Season_No { get; set; }
public string Image_Url_Big { get; set; }
public string TotalEpisode { get; set; }
}
}
Here is controller class:
public ActionResult ListAllSeason(string serial)
{
try
{
TvSerialDB tvcon = new TvSerialDB();
List<TVSerialByGroup> tv = tvcon.tvserialgroupby(serial).ToList();
return View(tv);
}
catch (Exception ex)
{
return Content(ex.Message);
}
}
When i run this application it does not display any record nor it gives error.
When i debug this code through breakpoint it returns rows into store procedure but in views it does not bind data.
You not adding your model instances to the collection.
while (sdr.Read())
{
TVSerialByGroup tvs = new TVSerialByGroup();
tvs.Series_Name = sdr["Series_Name"].ToString();
tvs.Image_Url_Big = sdr["Image_Url_Big"].ToString();
tvs.Season_No = sdr["Season_No"].ToString();
tvs.TotalEpisode = sdr["TotalEpisode"].ToString();
tvserials.Add(tvs); // add this
}
Side note: Since your initializing List<TVSerialByGroup>, you can make your method public List<TVSerialByGroup> tvserialgroupby(string serialname) and then you do not need .ToList(); in the ActionResult method.