Using ViewModels in asp.net mvc 3 - asp.net-mvc

Here is my scenario: (These all have to accomplished in the same view as an accepted requirement)
User enters a few search criterias to search users.
Page lists the search results with an update link besides.
User clicks on one of the update links and a form appears to enable editing the data.
User does changes and saves the data that binded to form.
I used a view model for this view. Here it is.
[Serializable]
public class UserAddModel
{
public UserSearchCriteria UserSearchCriteria { get; set; }
public UserEntity User { get; set; }
public List<UserPrincipalDto> SearchResults { get; set; }
}
And here is my controller:
using System;
namespace x.Web.BackOffice.Controllers
{
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
[Authorize(Roles = "Admin")]
public class UserController : Controller
{
private readonly IAuthentication _authentication;
private readonly List<RoleEntity> roles = new Y.Framework.Data.Repository<RoleEntity>().Get(null).ToList();
private Repository<UserEntity> repository = new Repository<UserEntity>();
[ImportingConstructor]
public UserController(IAuthentication authentication)
{
this._authentication = authentication;
}
public ActionResult Index()
{
return View(new UserAddModel());
}
[HttpPost]
public ActionResult GetSearchResults(UserAddModel model)
{
if (ModelState.IsValid)
{
try
{
List<UserPrincipalDto> results =
_authentication.SearchUsers(
ConfigurationManager.AppSettings["DomainName"],
model.UserSearchCriteria.FirstName,
model.UserSearchCriteria.LastName,
model.UserSearchCriteria.Username);
model.SearchResults = results;
Session["UserAddModel"] = model;
return View("Index", model);
}
catch (Exception ex)
{
Logger.Log(ex, User.Identity.Name);
}
}
else
{
ModelState.AddModelError("", "Error!");
}
Session["UserAddModel"] = model;
return View("Index", model);
}
public ActionResult Save(string username)
{
UserAddModel model = Session["UserAddModel"] as UserAddModel;
UserEntity exists = repository.Get(u => u.Username == username).FirstOrDefault();
if (exists == null)
{
UserPrincipal userPrincipal =
_authentication.GetUserDetails(
ConfigurationManager.AppSettings["DomainName"],
username);
model.User = new UserEntity();
model.User.Id = userPrincipal.Guid.Value;
model.User.FirstName = userPrincipal.DisplayName.FullNameToFirstName();
model.User.LastName = userPrincipal.DisplayName.FullNameToLastName();
model.User.Email = userPrincipal.EmailAddress;
model.User.Username = userPrincipal.SamAccountName;
}
else
{
model.User = new UserEntity();
model.User.Id = exists.Id;
model.User.FirstName = exists.FirstName;
model.User.LastName = exists.LastName;
model.User.Email = exists.Email;
model.User.Username = exists.Username;
model.User.RoleId = exists.RoleId;
}
ViewBag.Roles = roles;
return View("Index", model);
}
[HttpPost]
public ActionResult Save(UserAddModel model)
{
UserEntity exists = repository.Get(u => u.Id == model.User.Id).FirstOrDefault();
if (exists == null)
{
Result result = repository.Save(model.User);
HandleResult(result, model);
}
else
{
Result result = repository.Save(model.User, PageMode.Edit);
HandleResult(result, model);
}
ViewBag.Roles = roles;
return View("Index", model);
}
}
}
As you see there are two different forms in my view and I'm storing the whole view model in Session in my controller. But I think this is not fine enough. What if session expires or what if I have to deploy my application using a load balancer?
What is the best way to develop this kind of page? I'm open to any kind of suggestions.
Thanks in advance,

Related

WCF---Consuming CRUD operation using Linq in ASP.NET MVC application?

enter image description here
First step...Opened WCF created IService:
namespace CRUDOperationWCFMVC
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[OperationContract]
bool CreateDetails(EmployeeDetails employeeDetails);
[OperationContract]
bool UpdateDetails(EmployeeDetails employeeDetails);
[OperationContract]
bool DeleteDetails(int id);
[OperationContract]
List<EmployeeDetails> GetDetails();
}
public class EmployeeDetails
{
[DataMember]
public int EmpID { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Location { get; set; }
[DataMember]
public int? Salary { get; set; }
}
}
Step 2: then I implemented service code:
public class Service1 : IService1
{
DataClasses1DataContext dcd = new DataClasses1DataContext();
public bool CreateDetails(EmployeeDetails employeeDetails)
{
Nevint emp = new Nevint();
emp.EmpID= employeeDetails.EmpID;
emp.Name = employeeDetails.Name;
emp.Location = employeeDetails.Location;
emp.Salary = employeeDetails.Salary;
dcd.Nevints.InsertOnSubmit(emp);
dcd.SubmitChanges();
return true;
}
public bool DeleteDetails(int id)
{
var delete = (from v in dcd.Nevints where v.EmpID==id select v).FirstOrDefault();
dcd.Nevints.DeleteOnSubmit(delete);
dcd.SubmitChanges();
return true;
}
public List<EmployeeDetails> GetDetails()
{
List<EmployeeDetails> details = new List<EmployeeDetails>();
var select= (from v in dcd.Nevints select v);
foreach (var i in select)
{
EmployeeDetails emp = new EmployeeDetails();
emp.EmpID = i.EmpID;
emp.Name = i.Name;
emp.Location = i.Location;
emp.Salary = i.Salary;
details.Add(emp);
}
return details;
}
public bool UpdateDetails(EmployeeDetails employeeDetails)
{
var update = (from v in dcd.Nevints.ToList() where employeeDetails.EmpID==v.EmpID select v).FirstOrDefault();
update.EmpID = employeeDetails.EmpID;
update.Name = employeeDetails.Name;
update.Location = employeeDetails.Location;
update.Salary = employeeDetails.Salary;
dcd.SubmitChanges();
return true;
}
}
Step 3: then I add linq to sql, opened my ASP.NET MVC project for consuming, and added a controller and wrote this code:
namespace ConsumingClient.Controllers
{
public class EmpdetailsController : Controller
{
ServiceReference1.Service1Client serobj=new ServiceReference1.Service1Client();
ServiceReference1.EmployeeDetails empdetails=new ServiceReference1.EmployeeDetails();
// GET: Empdetails
public ActionResult Index()
{
List<employee> lstemp = new List<employee>();
var result = serobj.GetDetails();
foreach (var i in result)
{
employee emp = new employee();
empdetails.EmpID = i.EmpID;
empdetails.Name = i.Name;
empdetails.Location = i.Location;
empdetails.Salary = i.Salary;
lstemp.Add(emp);
}
return View(result);
}
// GET: Empdetails/Details/5
public ActionResult Details(int id)
{
Employees emp = new Employees();
return View();
}
// GET: Empdetails/Create
public ActionResult Create()
{
return View();
}
// POST: Empdetails/Create
[HttpPost]
public ActionResult Create(Employees employees)
{
try
{
// TODO: Add insert logic here
empdetails.EmpID=employees.EmpID;
empdetails.Name = employees.Name;
empdetails.Location = employees.Location;
empdetails.Salary = employees.Salary;
serobj.CreateDetails(empdetails);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Empdetails/Edit/5
public ActionResult Edit(int id)
{
Employees emp = new Employees();
var result = serobj.GetDetails().FirstOrDefault(a=>a.EmpID==id);
emp.EmpID = result.EmpID;
emp.Name = result.Name;
emp.Location = result.Location;
emp.Salary = result.Salary;
return View(emp);
}
// POST: Empdetails/Edit/5
[HttpPost]
public ActionResult Edit(Employees employees)
{
try
{
// TODO: Add update logic here
empdetails.EmpID = employees.EmpID;
empdetails.Name = employees.Name;
empdetails.Location = employees.Location;
empdetails.Salary = employees.Salary;
serobj.UpdateDetails(empdetails);
return RedirectToAction("Index");
}
catch
{
return View(employees);
}
}
// GET: Empdetails/Delete/5
public ActionResult Delete(int id)
{
Employees emp = new Employees();
var result = serobj.GetDetails().FirstOrDefault(a=>a.EmpID==id);
emp.EmpID = result.EmpID;
emp.Name = result.Name;
emp.Location = result.Location;
emp.Salary = result.Salary;
return View(emp);
}
// POST: Empdetails/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
serobj.DeleteDetails(id);
return RedirectToAction("Index");
}
catch
{
return View(id);
}
}
}
}
Data was displaying fine. I can create data.
However, when I click on edit and delete, I'm getting an error:
ERROR Message "Server Error in '/' Application.
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'ConsumingClient.Controllers.EmpdetailsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
This error is thrown if you attempt to call this controller action and you do not specify the id either in the path portion or as query string parameter. Since your controller action takes an id as parameter you should make sure that you always specify this parameter.
Make sure that when you are requesting this action you have specified a valid id in the url:
http://example.com/somecontroller/Edit/123
If you are generating an anchor, make sure there's an id:
#Html.ActionLink("Edit", "somecontroller", new { id = "123" })
If you are sending an AJAX request, also make sure that the id is present in the url.
If on the other hand the parameter is optional, you could make it a nullable integer:
public ActionResult Edit(int? id)
but in this case you will have to handle the case where the parameter value is not specified.
https://coderedirect.com/questions/197477/mvc-the-parameters-dictionary-contains-a-null-entry-for-parameter-k-of-non-n

How to load second partialview after success inserted in first partialview?

I have a view named Register.cshtml and 2 partialview named _AddUser.cshtml And _UserList.cshtml.
When I run the project shows register.cshtml and _AddUser.cshtml load in view. I want to load _UserList partialview after success inserted in _AddUser partialview.
DefaultController:
public class DefaultController : Controller
{
UserRepository UR = new UserRepository();
Automation_DBEntities database = new Automation_DBEntities();
[HttpGet]
public ActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(Users user, HttpPostedFileBase file)
{
UserRepository blUser = new UserRepository();
if (ModelState.IsValid)
{
///////////////////SaveImage
if (file != null)
{
if (user.UserImage != "no-photo.jpg")
{
if (System.IO.File.Exists(Server.MapPath("/image/UserImage/" + user.UserImage)))
System.IO.File.Delete(Server.MapPath("/image/UserImage/" + user.UserImage));
}
user.UserImage = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);
file.SaveAs(Server.MapPath("/image/UserImage/" + user.UserImage));
}
user.RegisterDate = DateTime.Now;
if (blUser.Add(user))
{
return PartialView("_UserList");//Inserted
}
else
{
}
}
else
{
}
}
[HttpGet]
public ActionResult AddUser()
{
return PartialView("~/Areas/Admin/Views/Shared/_AddUser.cshtml");
}
[HttpGet]
public ActionResult UserList()
{
IQueryable<AutomationSystem.Models.DomainModel.Users> list = UR.Select();
return PartialView("~/Areas/Admin/Views/Shared/_UserList.cshtml", list);
}

Get recent inserted Id and send in to another controllers view

EDITED:
I have Created CRUD Functions for each Modals and now i am trying to get recent Inserted Id and use it in different view.
Here is what I have tried so far
I have created 2 classes(Layer based) for CRUD function for each ContextEntities db to practice pure OOP recursive approach and following is the code.
1. Access Layer
ViolatorDB
public class ViolatorDB
{
private TPCAEntities db;
public ViolatorDB()
{
db = new TPCAEntities();
}
public IEnumerable<tbl_Violator> GetALL()
{
return db.tbl_Violator.ToList();
}
public tbl_Violator GetByID(int id)
{
return db.tbl_Violator.Find(id);
}
public void Insert(tbl_Violator Violator)
{
db.tbl_Violator.Add(Violator);
Save();
}
public void Delete(int id)
{
tbl_Violator Violator = db.tbl_Violator.Find(id);
db.tbl_Violator.Remove(Violator);
Save();
}
public void Update(tbl_Violator Violator)
{
db.Entry(Violator).State = EntityState.Modified;
Save();
}
public void Save()
{
db.SaveChanges();
}
}
2. Logic Layer
ViolatorBs
public class ViolatorBs
{
private ViolatorDB objDb;
public ViolatorBs()
{
objDb = new ViolatorDB();
}
public IEnumerable<tbl_Violator> GetALL()
{
return objDb.GetALL();
}
public tbl_Violator GetByID(int id)
{
return objDb.GetByID(id);
}
public void Insert(tbl_Violator Violator)
{
objDb.Insert(Violator);
}
public void Delete(int id)
{
objDb.Delete(id);
}
public void Update(tbl_Violator Vioaltor)
{
objDb.Update(Vioaltor);
}
}
And Finally using Logic Layer functions in presentation Layer.Here insertion is performed as:
public class CreateViolatorController : Controller
{
public TPCAEntities db = new TPCAEntities();
private ViolatorBs objBs;
public CreateViolatorController()
{
objBs = new ViolatorBs();
}
public ActionResult Index()
{
var voilator = new tbl_Violator();
voilator=db.tbl_Violator.Add(voilator);
ViewBag.id = voilator.VID;
return View();
}
[HttpPost]
public ActionResult Create(tbl_Violator Violator)
{
try
{
if (ModelState.IsValid)
{
objBs.Insert(Violator);
TempData["Msg"] = "Violator Created successfully";
return RedirectToAction("Index");
}
else
{
return View("Index");
}
}
catch (Exception ex)
{
TempData["Msg"] = "Failed..." + ex.Message + " " + ex.ToString();
return RedirectToAction("Index");
}
}
}
Now here is the main part how do i get perticuller inserted id in another controller named Dues while performing insertion ?
In sqlqery I would have used ##IDENTITY but in Entity Framework I'm not sure.
I'm new to mvc framework any suggestion or help is appreciated Thanks in Advance.
Once you save your db context the id is populated back to your entity by EF automatically.
for example.
using(var context = new DbContext())
{
var employee = new Employee(); //this has an id property
context.Employees.Add(employee);
context.SaveChanges();
var id = employee.id; // you will find the id here populated by EF
}
You dont need to add and save your table as you have done this already in your voilatorDB class just fetch the last id like following
var id = yourTableName.Id;
db.yourTableName.find(id);
Or you can simply write one line code to achive that using VoilatorBs class function
GetbyID(id);

Making Sessions in MVC 6 Controller(with views, using Entity Framework)

I'm attempting to create a session in my UserAccountsController
using System.Linq;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using POPPELWebsite.Models;
namespace POPPELWebsite.Controllers
{
public class UserAccountController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(UserAccount account)
{
if (ModelState.IsValid)
{
using (OurDbContext db = new OurDbContext())
{
db.userAccount.Add(account);
db.SaveChanges();
}
ModelState.Clear();
ViewBag.Message = account.FirstName + " " + account.LastName + " successfully registered.";
}
return View();
}
//Login
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(UserAccount user)
{
using (OurDbContext db = new OurDbContext())
{
var usr = db.userAccount.Single(u => u.Email == user.Email && u.Password == user.Password);
if (usr != null)
{
Session["UserID"] = usr.UserID.ToString;
}
}
}
}
}
I get an error saying
the name Session does not exist in the current context.
I need to do this part to complete a registration and login tutorial for mvc
The Session property does not exist in the Controller class in MVC 6, instead use HttpContext.Session to access the session property.
Ex:
// get values
string strValue = HttpContext.Session.GetString("StringKey");
int intValue = HttpContext.Session.GetInt32("IntKey");
byte[] byteArrayValue = HttpContext.Session.Get("ByteArrayKey");
// set values
HttpContext.Session.Set("ByteArrayKey", byteArrayValue);
HttpContext.Session.SetInt32("IntKey", intValue);
HttpContext.Session.SetString("StringKey", strValue);
Try this.
public ActionResult Login(User users)
{
if (ModelState.IsValid)
{
using (DataContext db = new DataContext())
{
var obj = db.Users.Where(u => u.Username.Equals(users.Username) && u.Password.Equals(users.Password)).FirstOrDefault();
if(obj !=null)
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
context.Session["UserId"] = obj.UserId.ToString();
context.Session["Username"] = obj.Username.ToString();
return RedirectToAction("Dashboard");
}
}
}
return View(users);
}

How to Edit Two Model in one View EntityFramework.dll error

This my Code
Model
public class ViewModelRequestPurchaseItem
{
public List<RequestPurchase> RequestPurchases { get; set; }
public List<RequestPurchaseItem> RequestPurchaseItems { get; set; }
}
View
#using EFMySQLCardTest.Models
#model EFMySQLCardTest.Models.ViewModelRequestPurchaseItem
Controller
public ActionResult Edit([Bind(Include = "RequestPurchases,RequestPurchaseItems")] ViewModelRequestPurchaseItem viewModelRequestPurchaseItem, string id)
{
var requestPurchase = db.RequestPurchase.Where(x => x.RequestPurchaseNumber == id).ToList();
var requestPurchaseItem = db.RequestPurchaseItem.Where(x => x.RequestPurchaseNumber == id).OrderBy(x => x.RequestPurchaseItemID).ToList();
viewModelRequestPurchaseItem.RequestPurchases = requestPurchase;
viewModelRequestPurchaseItem.RequestPurchaseItems = requestPurchaseItem;
if (ModelState.IsValid)
{
db.Entry(viewModelRequestPurchaseItem).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
this.ExpendErrors();
}
return View(viewModelRequestPurchaseItem);
}
In this line:
db.Entry(viewModelRequestPurchaseItem).State = EntityState.Modified
the error is:
viewModelRequestPurchaseItem is not model of parts
ViewModelRequestPurchaseItem is your view model and is not part of the database context. You need to save each RequestPurchase and RequestPurchaseItems in the collections. You current code is also assigning the collections to the current values in the database, wiping out any edits you have made in the view. Your method should be
public ActionResult Edit(ViewModelRequestPurchaseItem model)
{
if (ModelState.IsValid)
{
return View(model);
}
foreach (RequestPurchase item in model.RequestPurchases)
{
db.Entry(item).State = EntityState.Modified;
}
// ditto for RequestPurchaseItems
db.SaveChanges();
return RedirectToAction("Index");
}

Resources