I am developing an application in MVC 5 and perform CRUD operations on it.
I have successfully added Northwind database as an Entity Data Model and taking Customer in the Model. Now with the help of Scaffolding I generated the CustomersController.
When I create a new record in a Customer Table. There is no problem.
But when I click on that new record, Edit, Details and Delete are not working. After clicking any of these:
The following page occurs:
My Controller Code:
namespace MvcNorthwindSample.Controllers
{
public class CustomersController : Controller
{
private NORTHWNDEntities db = new NORTHWNDEntities();
// GET: Customers
public ActionResult Index()
{
return View(db.Customers.ToList());
}
// GET: Customers/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
return View(customer);
}
// GET: Customers/Create
public ActionResult Create()
{
return View();
}
// POST: Customers/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CustomerID,CompanyName,ContactName,ContactTitle,Address,City,Region,PostalCode,Country,Phone,Fax")] Customer customer)
{
if (ModelState.IsValid)
{
db.Customers.Add(customer);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(customer);
}
// GET: Customers/Edit/5
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
return View(customer);
}
// POST: Customers/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "CustomerID,CompanyName,ContactName,ContactTitle,Address,City,Region,PostalCode,Country,Phone,Fax")] Customer customer)
{
if (ModelState.IsValid)
{
db.Entry(customer).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(customer);
}
// GET: Customers/Delete/5
public ActionResult Delete(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
return View(customer);
}
// POST: Customers/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string id)
{
Customer customer = db.Customers.Find(id);
db.Customers.Remove(customer);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
My View Part:
My Create Code Result view while debugging:
EDIT: After you posted your controller:
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
Are you sure that you have a customer with an id of 1994? If not, your logic would return HttpNotFound().
In the screenshot you posted, I can read HTTP 404 error message and the requested URL was /Customer/Edit/1994.
So for that I assume you must be have the following controller/action:
public class CustomerController
{
public ActionResult Edit(int id)
{
return View();
}
}
Now the most common mistake most people make (including me) is properly passing id in the URL. You have id specified as an optional parameter in your route pattern:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
So if you don't want to use id you could pass something else as a key name in the the query component, e.g., /Customer/Edit?year=1994.
The error is a 404 Error.
It is looking in the Controller Customers for an Edit action.
Also pointed out in the comments the Id 1994 has a encoded space character following it. If the id is suppose to be strings, you can change the parameter to type string instead of int
public class CustomersController
{
public ActionResult Edit(int id)
{
return View();
}
}
I solved it. I changed the table at last. There is a problem on the table named Customers of the Northwind database. I download database backup file. The Customer ID column is adding a space as a default with the inserted value.
First create your models and Dbcontext.
public class TaskManagerContext : DbContext
{
public TaskManagerContext()
: base("TaskManagerDB")
{
}
public DbSet<User> Users { get; set; }
public DbSet<Task> Tasks { get; set; }
}
Then allow migrations and update the database from the PM. Create a folder Repositories with a BaseRepo that the rest must inherit.
public class BaseRepository<T> where T:BaseModel, new()
{
protected TaskManagerContext context;
protected DbSet<T> dbSet;
public BaseRepository()
{
this.context = new TaskManagerContext();
this.dbSet = this.context.Set<T>();
}
public void Insert(T item)
{
this.dbSet.Add(item);
this.context.SaveChanges();
}
public void Update(T item)
{
this.context.Entry(item).State = EntityState.Modified;
this.context.SaveChanges();
}
public void Delete(int id)
{
this.dbSet.Remove(this.dbSet.Find(id));
this.context.SaveChanges();
}
public IEnumerable<T> GetAll()
{
return this.dbSet;
}
}
like this:
public class UsersRepository : BaseRepository<User>
{
public UsersRepository()
: base()
{
}
}
Then you create the controllers in which you use the methods from the repos.
public class UsersController : Controller
{
//
// GET: /Users/
public ActionResult List()
{
List<User> users = new List<User>();
users = new UsersRepository().GetAll().ToList();
return View(users);
}
public ActionResult Edit(int id)
{
User user = new UsersRepository().GetAll().FirstOrDefault(u => u.ID == id);
return View(user);
}
[HttpPost]
public ActionResult Edit(User user)
{
UsersRepository repo = new UsersRepository();
repo.Update(user);
return RedirectToAction("List");
}
public ActionResult Delete(int id)
{
UsersRepository repo = new UsersRepository();
repo.Delete(id);
return RedirectToAction("List");
}
public ActionResult Create()
{
User u = new User();
return View(u);
}
[HttpPost]
public ActionResult Create(User user)
{
UsersRepository repo = new UsersRepository();
repo.Insert(user);
return RedirectToAction("List");
}
}
The actions for the TaskContr are simillar exept the List in which you connect the 2 models by ID:
public ActionResult List(int? id)
{
TasksRepository repo = new TasksRepository();
List<Task> tasks = new List<Task>();
tasks = repo.GetAll().Where(t => t.UserID == id).ToList();
return View(tasks);
}
Don't forget to generate views(on the Get methods) and change the List view for the Users:
#Html.ActionLink("Details", "List", "Tasks", new { id=item.ID }, null) |
That way when clicking Details you can see the tasks for that user.
public ActionResult Index()
{
using (DevExam db = new DevExam())
{
var intern = from m in db.Interns
select m;
return View(intern.ToList());
}
/* using (DevExam db = new DevExam())
{
var interns = db.Interns
.Include(s => s.InternID)
.Select(s => new Intern
{
InternID = s.InternID,
lname = s.lname,
fname = s.fname
});
return View(interns);
}
*/
}
// GET: CRUD/Details/5
public ActionResult Details(int id)
{
using (DevExam db = new DevExam())
{
return View(db.Interns.Where(x => x.InternID == id).FirstOrDefault());
}
}
// GET: CRUD/Create
public ActionResult Create()
{
return View();
}
// POST: CRUD/Create
[HttpPost]
public ActionResult Create(Intern intern)
{
try
{
// TODO: Add insert logic here
using (DevExam db = new DevExam())
{
db.Interns.Add(intern);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: CRUD/Edit/5
public ActionResult Edit(int id)
{
using (DevExam db = new DevExam())
{
return View(db.Interns.Where(x => x.InternID == id).FirstOrDefault());
}
}
// POST: CRUD/Edit/5
[HttpPost]
public ActionResult Edit(int id,Intern intern)
{
try
{
// TODO: Add update logic here
using (DevExam db = new DevExam())
{
db.Entry(intern).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: CRUD/Delete/5
public ActionResult Delete(int id)
{
using (DevExam db = new DevExam())
{
return View(db.Interns.Where(x => x.InternID == id).FirstOrDefault());
}
}
// POST: CRUD/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
using (DevExam db = new DevExam())
{
Intern intern = db.Interns.Where(x => x.InternID == id).FirstOrDefault();
db.Interns.Remove(intern);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
create table tblemployee(
EmpId int NOT NULL identity(1,1),
EmpName varchar(100),
PhoneNumber varchar(10),
Country int,
State int,
maritalstetus varchar(50),
isvoting varchar(50),
dob datetime,
doj datetime
primary key (EmpId)
)
create table tblCountry(
Id int NOT NULL identity(1,1),
Name varchar(100),
primary key (Id)
)
insert into tblCountry(Name) values ('India')
insert into tblCountry(Name) values ('US')
insert into tblCountry(Name) values ('UK')
create table tblstate(
Id int NOT NULL identity(1,1),
Name varchar(100),
countryId int,
primary key (Id)
)
insert into tblstate(Name ,countryId) values ('Delhi',1)
insert into tblstate(Name , countryId) values ('Bihar' ,1)
insert into tblstate(Name , countryId) values ('Up',1)
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Xml.Linq;
namespace webTest.Models
{
public class Employee
{
public int id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string PhoneNumber { get; set; }
[Required]
public int Country { get; set; }
[Required]
public int State { get; set; }
[Required]
public bool MarritalStatus { get; set; }
public bool IsVoting { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime DOB { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime DOJ { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using webTest.Models;
namespace webTest.Controllers
{
public class EmpController : Controller
{
// GET: Emp
public static string constr = "Data Source=DIVYANSHU;Initial Catalog=EmployeeData;Integrated Security=True";
SqlConnection conn = new SqlConnection(constr);
public ActionResult ViewList()
{
List<Employee> employees = new List<Employee>();
try
{
conn.Open();
string sqlquery = "select * from tblEmployee";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Employee emp = new Employee()
{
id = Convert.ToInt32(dr["Empid"].ToString().Trim()),
Name = dr["EmpName"].ToString(),
PhoneNumber = dr["PhoneNumber"].ToString(),
Country = Convert.ToInt32(dr["Country"].ToString().Trim()),
State = Convert.ToInt32(dr["State"].ToString().Trim()),
MarritalStatus = Convert.ToBoolean(dr["maritalstetus"].ToString().Trim()),
IsVoting = Convert.ToBoolean(dr["isvoting"]),
DOB = Convert.ToDateTime(dr["dob"].ToString().Trim()),
DOJ = Convert.ToDateTime(dr["doj"].ToString().Trim()),
};
employees.Add(emp);
}
conn.Close();
}
catch (Exception ex)
{
}
return View(employees);
}
public ActionResult Create()
{
SqlDataAdapter _da = new SqlDataAdapter("Select * From tblCountry", constr);
DataTable _dt = new DataTable();
_da.Fill(_dt);
ViewBag.Country = ToSelectList(_dt, "Id", "Name");
_da.Dispose();
SqlDataAdapter _da1 = new SqlDataAdapter("Select * From tblState", constr);
DataTable _dt1 = new DataTable();
_da1.Fill(_dt1);
ViewBag.State = ToSelectList(_dt1, "Id", "Name");
_da1.Dispose();
Employee emp = new Employee();
return View(emp);
}
public SelectList ToSelectList(DataTable table, string valueField, string textField)
{
List<SelectListItem> list = new List<SelectListItem>();
foreach (DataRow row in table.Rows)
{
list.Add(new SelectListItem()
{
Text = row[textField].ToString(),
Value = row[valueField].ToString()
});
}
return new SelectList(list, "Value", "Text");
}
[HttpPost]
public ActionResult Create(Employee empmodel)
{
List<Employee> employees = new List<Employee>();
try
{
conn.Open();
string sqlquery = "insert into tblEmployee(EmpName,PhoneNumber,Country,State,maritalstetus,isvoting,dob,doj) values('" + empmodel.Name + "','" + empmodel.PhoneNumber + "'," + empmodel.Country + "," + empmodel.State + ",'" + empmodel.MarritalStatus + "','" + empmodel.IsVoting + "','" + empmodel.DOB + "','" + empmodel.DOJ + "')";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
cmd.ExecuteNonQuery();
conn.Close();
employees = listEmployee();
}
catch (Exception ex)
{
}
return View("ViewList", employees);
}
public ActionResult Edit(int id)
{
Employee emp = new Employee();
try
{
SqlDataAdapter _da = new SqlDataAdapter("Select * From tblCountry", constr);
DataTable _dt = new DataTable();
_da.Fill(_dt);
ViewBag.Country = ToSelectList(_dt, "Id", "Name");
_da.Dispose();
SqlDataAdapter _da1 = new SqlDataAdapter("Select * From tblState", constr);
DataTable _dt1 = new DataTable();
_da1.Fill(_dt1);
ViewBag.State = ToSelectList(_dt1, "Id", "Name");
_da1.Dispose();
conn.Open();
string sqlquery = "select * from tblemployee where empid=" + id + "";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
emp = new Employee()
{
id = Convert.ToInt32(dr["Empid"].ToString().Trim()),
Name = dr["EmpName"].ToString(),
PhoneNumber = dr["PhoneNumber"].ToString(),
Country = Convert.ToInt32(dr["Country"].ToString().Trim()),
State = Convert.ToInt32(dr["State"].ToString().Trim()),
MarritalStatus = Convert.ToBoolean(dr["maritalstetus"].ToString().Trim()),
IsVoting = Convert.ToBoolean(dr["isvoting"]),
DOB = Convert.ToDateTime(dr["dob"].ToString().Trim()),
DOJ = Convert.ToDateTime(dr["doj"].ToString().Trim()),
};
}
conn.Close();
}
catch (Exception ex)
{
}
return View(emp);
}
[HttpPost]
public ActionResult Edit(Employee empmodel)
{
try
{
conn.Open();
string sqlquery = "update tblEmployee set EmpName='" + empmodel.Name + "',PhoneNumber='" + empmodel.PhoneNumber + "',Country=" + empmodel.Country + ",State=" + empmodel.State + ",maritalstetus='" + empmodel.MarritalStatus + "',isvoting='" + empmodel.IsVoting + "',dob='" + empmodel.DOB + "',doj='" + empmodel.DOJ + "' where empid=" + empmodel.id + "";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
}
List<Employee> list = listEmployee();
return View("ViewList", list);
}
public ActionResult Delete(int id)
{
try
{
conn.Open();
string sqlquery = "Delete from tblEmployee where empid=" + id + "";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
}
List<Employee> list = listEmployee();
return View("ViewList", list);
}
public List<Employee> listEmployee()
{
List<Employee> employees = new List<Employee>();
conn.Open();
string sqlquery = "select * from tblEmployee";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Employee emp = new Employee()
{
id = Convert.ToInt32(dr["Empid"].ToString().Trim()),
Name = dr["EmpName"].ToString(),
PhoneNumber = dr["PhoneNumber"].ToString(),
Country = Convert.ToInt32(dr["Country"].ToString().Trim()),
State = Convert.ToInt32(dr["State"].ToString().Trim()),
MarritalStatus = Convert.ToBoolean(dr["maritalstetus"].ToString().Trim()),
IsVoting = Convert.ToBoolean(dr["isvoting"]),
DOB = Convert.ToDateTime(dr["dob"].ToString().Trim()),
DOJ = Convert.ToDateTime(dr["doj"].ToString().Trim()),
};
employees.Add(emp);
}
conn.Close();
return employees;
}
}
}
//in Edit view and in create view replace edit for to
#Html.DropDownListFor(model => model.Country, ViewBag.Country as SelectList, new { #class = "form-control" })
#Html.DropDownListFor(model => model.State, ViewBag.State as SelectList, new { #class = "form-control" })
Related
I get error using #Html.DropDownListFor for edit session, I use it for create method is succes, but when I use in edit method is fail, the error warning like this System.InvalidOperationException: 'There is no ViewData item of type 'IEnumerable' that has the key 'roles_id'.' .
The deail file like this:
Edit.cshtml:
<div class="form-group">
#Html.LabelFor(model => model.roles, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-12">
#Html.DropDownListFor(model => model.roles_id, (SelectList)ViewBag.RolesList, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.roles_id, "", new { #class = "text-danger" })
</div>
</div>
EmployeeController.cs
// GET: Employee/Edit/{id}
public ActionResult Edit(int id)
{
AuthDBHandle dbhandle = new AuthDBHandle();
adminlteDBHandle sdb = new adminlteDBHandle();
var roles_id = sdb.GetEmployee().Find(smodel => smodel.employee_id == id).roles_id;
var roles = dbhandle.GetRoles();
ViewBag.RolesList = new SelectList(roles, "roles_id", "roles", roles_id);
return View(sdb.GetEmployee().Find(smodel => smodel.employee_id == id));
}
// POST: Employee/Edit/{id}
[HttpPost]
public ActionResult Edit(EmployeeViewModel smodel)
{
try
{
if (ModelState.IsValid)
{
adminlteDBHandle sdb = new adminlteDBHandle();
if (sdb.EditEmployee(smodel))
{
ViewBag.Message = "Edit employee is success";
ModelState.Clear();
return RedirectToAction("Index");
}
return View();
}
return View();
}
catch
{
return View();
}
}
EmployeeViewModel.cs
namespace adminlte.Models
{
public class EmployeeViewModel
{
[Display(Name = "Employee Id")]
public int employee_id { get; set; }
[Required(ErrorMessage = "Fullname is required.")]
public string fullname { get; set; }
[Required(ErrorMessage = "Address is required.")]
[DataType(DataType.MultilineText)]
public string address { get; set; }
public string roles { get; set; }
[Required(ErrorMessage = "Role ID is required.")]
public int roles_id { get; set; }
[Required(ErrorMessage = "Email is required.")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string email { get; set; }
public string password { get; set; }
}
}
I don't know why, I try to look for an example but fail all, please help me to solve this problem.
Thanks.
Data you put in the ViewBag is not persisted between requests. When you try to display your view again, you need to repopulate the ViewBag items.
I generally extract the code to populate the lookups to a separate method, which avoids duplication.
Eg:
private void PopulateLookups(EmployeeViewModel vm)
{
AuthDBHandle dbhandle = new AuthDBHandle();
var roles = dbhandle.GetRoles();
ViewBag.RolesList = new SelectList(roles, "roles_id", "roles", vm.roles_id);
}
// GET: Employee/Edit/{id}
public ActionResult Edit(int id)
{
adminlteDBHandle sdb = new adminlteDBHandle();
var employee = sdb.GetEmployee().Find(smodel => smodel.employee_id == id);
if (model == null) return RedirectToAction("Index");
var vm = new EmployeeViewModel
{
employee_id = employee.employee_id,
fullname = employee.fullname,
address = employee.address,
roles = employee.roles,
roles_id = employee.roles_id,
email = employee.email,
password = employee.password, // WARNING!
};
PopulateLookups(vm);
return View(vm);
}
// POST: Employee/Edit/{id}
[HttpPost]
public ActionResult Edit(EmployeeViewModel vm)
{
try
{
if (ModelState.IsValid)
{
adminlteDBHandle sdb = new adminlteDBHandle();
if (sdb.EditEmployee(vm))
{
return RedirectToAction("Index");
}
}
PopulateLookups(vm);
return View();
}
catch
{
PopulateLookups(vm);
return View();
}
}
NB: Based on your column names, you appear to be storing the employees' passwords in plain text. Don't do that! Store a salted hash of the password, using multiple iterations of a cryptographically-secure one-way hashing algorithm.
//Student Controller
public class Student
{
[Key]
public int StudentId { get; set; }
public string Name { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Emial { get; set; }
public string Role { get; set; }
}
//StudentConroller (Here I called Stored Procedure)
public class AccountController : Controller
{
public ApplicationDbClass applicationDbClass;
public AccountController()
{
applicationDbClass = new ApplicationDbClass();
}
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(Student student)
{
var v1 = new SqlParameter();
v1.ParameterName = "#role";
v1.SqlDbType = SqlDbType.NVarChar;
v1.Value = "Admin";
var v2 = new SqlParameter();
v2.ParameterName = "#count";
v2.SqlDbType = SqlDbType.Int;
try
{
var result = applicationDbClass.Students.SqlQuery("StudentProcedure #role,#count OUT", v1, v2).ToArray();
}
catch(Exception e)
{
var m = e.Message;
}
return RedirectToAction("Welcome", "Student");
}
}
//Stored procedure
CREATE OR ALTER PROCEDURE StudentProcedure
#role NVARCHAR(30),
#count INT OUTPUT
AS
BEGIN
SELECT #count=COUNT(dbo.Students.Role)
FROM dbo.Students
WHERE Role=#role;
END
//DbContext Class
public class ApplicationDbClass : DbContext
{
public ApplicationDbClass() : base()
{
Database.SetInitializer<ApplicationDbClass>(new DropCreateDatabaseIfModelChanges<ApplicationDbClass>());
}
public DbSet<Student> Students { get; set; }
public DbSet<LogTable> LogTables { get; set; }
}
// Here I am using code first approch to deal with database using entity framework to call the user created stored procedure. If I make some changes on stored procedure it will not refected directly. Please give me any solution to refects the changes.
You can pass parameters in this way also
SqlConnection cnn = new SqlConnection(cnnString);
SqlCommand cmd = new SqlCommand("StudentProcedure", cnn);
cmd.Connection = cnn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#role", "Admin");
cmd.Parameters.Add("#count", SqlDbType.Int);
cmd.Parameters["#count"].Direction = ParameterDirection.Output;
string Query = cmd.ExecuteNonQuery().ToString();
Here my goal is to show how to pass normal and output parameter to procedure.
There are two issues here in your code.
You should set the default value for your output parameter. Otherwise C# code will throw an exception if you do not set default value to your output parameter. So your stored procedure should look like this:
ALTER PROCEDURE StudentProcedure
#role NVARCHAR(30),
#count INT = NULL OUTPUT
AS
BEGIN
SELECT #count=COUNT(dbo.Students.Role)
FROM dbo.Students
WHERE Role=#role;
SELECT #count;
END
GO
And the second issue is you've forgot to set Direction of your output parameter:
var sqlParameter_Role = new SqlParameter("#role", "Admin");
var sqlParameter_Count = new SqlParameter();
sqlParameter_Count.ParameterName = "#count";
sqlParameter_Count.SqlDbType = SqlDbType.Int;
sqlParameter_Count.Direction = ParameterDirection.Output;
var result = db.Database
.SqlQuery<ResultForStudentProcedure>("dbo.StudentProcedure #role"
, sqlParameter_Role
, sqlParameter_Count)
.ToList();
public class ResultForStudentProcedure
{
public int Count { get; set; }
}
So, I recently found quite an issue with my site: when it first loads, a section of the website is missing. After some tests, I found that this line was sometimes false: #if (Model != null && Model.Any()). After a test using a single Modal == null, I found that yes, the issue is that it's sometimes null. Also, I found that the best way for me to reproduce the issue (no error messages) is to restart visual studio. CTRL + F5 does not make it be null. Any ideas why is that ?
Here's the Model and the part of cshtml:
public class BlogModel
{
public int Id { get; set; }
public bool AfficheAuteur { get; set; }
public string Alias { get; set; }
public string Sujet { get; set; }
public string Auteur { get; set; }
public string Photo { get; set; }
public int? Ordre { get; set; }
public PostModel Post { get; set; }
}
public class PostModel
{
public int Id { get; set; }
public string Alias { get; set; }
public string Nom { get; set; }
}
//.cshtml:
#model IList<Project.Models.Shared.BlogModel>
//...
#if (Model != null && Model.Any())
//...
Note that I'm using asp.net Core MVC with razor.
Edit:
public static IList<BlogModel> GetBlogs()
{
var _lock = new object();
var strKey = string.Format("Home-Blogs-{0}", Site.Id);
var blogs = (IList<BlogModel>)CacheManager.Get(strKey);
if (blogs == null)
{
lock (_lock)
{
blogs = (IList<BlogModel>)CacheManager.Get(strKey);
if (blogs == null)
{
using (var context = new DB())
{
context.Configuration.LazyLoadingEnabled = false;
var nIdSite = Site.Id;
var bl = (from b in context.Blog
where b.Actif &&
(b.IdsSite.Contains("," + nIdSite + ",")) &&
b.Posts.Any(y => y.Publier)
orderby b.Ordre
select new BlogModel()
{
Id = b.Id,
AfficheAuteur = b.AfficherAuteur,
Alias = b.Alias,
Sujet = b.Sujet,
Photo = b.Image,
Auteur = b.User.Profile.FirstName + " " + b.User.Profile.LastName,
Ordre = b.Ordre,
Post = (from p in context.BlogPost
where p.Publier &&
p.IdBlog == b.Id &&
p.DateAffichage <= DateTime.Now
orderby p.DateAffichage descending
select new PostModel()
{
Id = p.Id,
Alias = p.Alias,
Nom = p.Nom
}).FirstOrDefault()
}).ToList();
CacheManager.Insert(strKey, bl, null, 10800, Cache.NoSlidingExpiration, CacheItemPriority.High, null);
return blogs;
}
}
}
}
return blogs;
}
public ActionResult Index(GridSettings settings, string strQuery)
{
var model = new IndexBlogViewModel(settings, blogService, strQuery);
ViewBag.FilAriane.Add(new KeyValuePair<string, string>(Url.Action("Index", "Home"), "Accueil"));
ViewBag.FilAriane.Add(new KeyValuePair<string, string>("", "Blogs"));
return View(model);
}
[HttpGet]
public ActionResult Create()
{
var model = new BlogFormViewModel { Blog = new Entitie.Blog { IdSite = IdSite } };
var lstUser = new List<User>();
var cfUserProvider = new CFUserProvider();
foreach (var mu in cfUserProvider.GetAllUsers().Cast<MembershipUser>())
{
var r = new CFRoleProvider();
if (r.IsUserInRole(mu.UserName, "Bloggeur"))
{
var u = new User { Username = mu.UserName, Id = Convert.ToInt32(mu.ProviderUserKey) };
lstUser.Add(u);
}
}
model.User = lstUser.Select(x => new SelectListItem
{
Text = x.Username,
Value = x.Id.ToString()
});
model.Sites = siteService.GetAll(x => x.IdEntreprise == IdEntreprise)
.Select(x => new CheckBoxListItem
{
Id = x.Id,
Display = x.Nom,
IsChecked = false
}).ToList();
ViewBag.FilAriane.Add(new KeyValuePair<string, string>(Url.Action("Index", "Home"), "Accueil"));
ViewBag.FilAriane.Add(new KeyValuePair<string, string>("", "Blog"));
return View(model);
}
Found it... It was checking for null and if it was, was adding it to cache but still returning the non-updated variable. Simply had to update it before returning...
Added:
blogs = (IList<BlogModel>)CacheManager.Get(strKey);
before returning.
I have tried to send data as a string and it is working correctly. but now i want to insert all gridview data as a list into database. Code is here
public interface IService1
{
[OperationContract]
string InsertCustomerDetails(UserDetails userInfo);
[OperationContract]
[WebGet]
List<CustomerTable> GetCustomers();
}
public class UserDetails
{
string Name = string.Empty;
string City = string.Empty;
[DataMember]
public string name
{
get { return Name; }
set { Name = value; }
}
[DataMember]
public string city
{
get { return City; }
set { City = value; }
}
public class Service1 : IService1
{
public string InsertCustomerDetails(UserDetails userInfo)
{
using(DataContext db=new DataContext())
{
CustomerTable customer = new CustomerTable();
customer.Name = userInfo.name;
customer.City = userInfo.city;
db.CustomerTables.Add(customer);
db.SaveChanges();
}
return "name= " + userInfo.name + " city= " + userInfo.city;
}
}
}
WEB Form Code
protected void ButtonADD_Click(object sender, EventArgs e)
{
for (int i = 0; i < GridView2.Rows.Count; i++) {
UserDetails info = new UserDetails();
info.name = GridView2.Rows[i].Cells[0].Text;
info.city = GridView2.Rows[i].Cells[1].Text;
obj.InsertCustomerDetails(info);
} }
In Iservice1 class use this
public List<CustomerTable> InsertCustomerDetails(UserDetails userInfo)
{
using(DataContext db=new DataContext())
{
CustomerTable customer = new CustomerTable();
customer.Name = userInfo.name;
customer.City = userInfo.city;
db.CustomerTables.Add(customer);
db.SaveChanges();
return db.CustomerTables.ToList();
}
Use this in interface. Make setter getters in class UserDetails
[OperationContract]
List<CustomerTable> InsertCustomerDetails(UserDetails userInfo);
I Have done this. Just facing problem in Web Form. Any Help will be appriciated. I want to send dqata as list into database
I am struck at this code, i get this error when whenever i tried to see a list of articles.
the error is The parameters dictionary contains a null entry for parameter articleId of non-nullable type System.Int32 for method System.Web.Mvc.ActionResult Detail(Int32) in Crossroads.Controllers.ArticleController. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters.
Here is the controller:
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Security;
using Crossroads.Models;
using System.Linq;
using System.Web;
using Crossroads.Models.Repositories;
namespace Crossroads.Controllers
{
[HandleError]
public class ArticleController : BaseController
{
private IArticleRepository _ArticleRepository;
public ArticleController()
: this(new ArticleRepository())
{ }
public ArticleController(IArticleRepository articleRepo)
{
_ArticleRepository = articleRepo;
}
public ActionResult Index(bool? archived)
{
if (archived != null && archived.Value.Equals(true))
{
return View("IndexArchived", _ArticleRepository.ListArchivedArticles());
}
else
{
return View(_ArticleRepository.ListArticles());
}
}
public ActionResult Detail(int Id)
{
var article = _ArticleRepository.GetArticle(Id);
if (article.Published)
{
return View("Details", article);
}
else
{
postStatus = new PostStatusViewModel()
{
Status = Status.Warning,
Message = "I'm sorry, article " + article.Title + " has been deleted. <br />Please update your bookmark."
};
return RedirectToAction("PostStatus", postStatus);
}
}
public ActionResult Details(int id, string articleTitle)
{
return RedirectToAction("Detail", id);
}
[Authorize(Roles = "Manager")]
public ActionResult New()
{
return View("New", new Articles());
}
[Authorize(Roles = "Manager")]
[ValidateInput(false)]
public ActionResult Edit(int id)
{
var viewModel = _ArticleRepository.GetArticle(id);
return View(_ArticleRepository.GetArticle(id));
}
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
[Authorize(Roles = "Manager")]
public ActionResult Create(Articles model)
{
try
{
model.CreatedBy = Membership.GetUser().UserName;
model.CreatedDate = DateTime.Now;
model.ModifiedBy = Membership.GetUser().UserName;
model.ModifiedDate = DateTime.Now;
_ArticleRepository.CreateArticle(model);
return RedirectToAction("Index");
}
catch
{
return View("Edit", model.Id);
}
}
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
[Authorize(Roles = "Manager")]
public ActionResult Update(Articles model)
{
try
{
model.ModifiedBy = Membership.GetUser().UserName;
model.ModifiedDate = DateTime.Now;
_ArticleRepository.EditArticle(model);
return RedirectToAction("Details", new { id = model.Id });
}
catch (Exception ex)
{
_DBLogging.LoggError(ex);
postStatus = new PostStatusViewModel()
{
Status = Status.Error,
Message = ""
};
return View("Edit");
}
}
public JsonResult ManageArchiveArticle(int articleId, bool isArchived)
{
var result = new Dictionary<string, string>();
try
{
var article = _ArticleRepository.GetArticle(articleId);
article.IsArchived = isArchived ? false : true;
article.ModifiedBy = Membership.GetUser().UserName;
article.ModifiedDate = DateTime.Now;
if (article.IsArchived) article.ArchiveDate = DateTime.Now;
article = _ArticleRepository.EditArticle(article);
result.Add("isArchived", article.IsArchived.ToString().ToLower());
}
catch (Exception ex)
{
_DBLogging.LoggError(ex);
}
return Json(result);
}
public JsonResult ManagePublishArticle(int articleId, bool isPublished)
{
var result = new Dictionary<string, string>();
try
{
var article = _ArticleRepository.GetArticle(articleId);
article.Published = isPublished ? false : true;
article.ModifiedBy = Membership.GetUser().UserName;
article.ModifiedDate = DateTime.Now;
article = _ArticleRepository.EditArticle(article);
result.Add("isPublished", article.Published.ToString().ToLower());
}
catch (Exception ex)
{
_DBLogging.LoggError(ex);
}
return Json(result);
}
}
}
here is my index
<ul class="menu">
<li><%= Html.ActionLink("Article List", "Index", "Article")%></li>
<li><%= Html.ActionLink("New Article", "New", "Article")%></li>
</ul>