ID identity field value does not increase - asp.net-mvc

I have a form to bind id field as hidden value. But in controller, the id (key, auto identity increment) field always 0. Below is my code:
Model.cs
public partial class A
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
[StringLength(255)]
[Display(Name = "Institution Name")]
[Required]
public string InstitutionName { get; set; }
[Display(Name = "Public")]
[DefaultValue(false)]
public bool Category1 { get; set; }
[Display(Name = "Private")]
[DefaultValue(false)]
[Display(Name = "Online")]
[DefaultValue(false)]
public bool Category3 { get; set; }
[
[Display(Name = "Active?")]
[DefaultValue(false)]
public bool active { get; set; }
public A()
{
Category1 = false;
Category2 = false;
Category3 = false;
active = true;
}
}
Controller:
...
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "id,InstitutionName,Category1,Category2,Category3,active")] A A)
{
if (ModelState.IsValid)
{
db.A.Add(A);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(A);
}
}
...
View - Create.cshtml:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>TransferSearch_revised</h4>
<hr />
#Html.HiddenFor(model=> model.id)
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.InstitutionName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.InstitutionName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.InstitutionName, "", new { #class = "text-danger" })
</div>
</div>
...
The id value either 0 or empty. What's wrong with my code? Thanks.

Related

Drop down list binding from another model in MVC

I am new to asp.net mvc
I have two tables tblEmployee and tblDepartment in both the tables common field is department id.
If the user creating new employee they have to select their department list from tblDepartment table.I am getting list of departments from that table there is no issue in that,but when i submitting the form departmentid is going null into the DB.
Models
public partial class Department
{
public Department()
{
this.tblEmployees = new HashSet<Employee>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Employee> tblEmployees { get; set; }
public Employee employee { get; set; }
}
public partial class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
public Nullable<int> DepartmentId { get; set; }
public virtual Department tblDepartment { get; set; }
public List<Department> deprtment { get; set; }
public virtual string Department { get; set; }
public bool available { get; set; }
}
Controller:
public ActionResult Create()
{
SampleDbContext Db = new SampleDbContext();
List<Employee> employees = Db.Employees.Include("tblDepartment").ToList();
ViewBag.list = new SelectList(Db.Departments, "Id", "Name");
return View();
}
[HttpPost]
public ActionResult Create( Employee employee)
{
SampleDbContext Db = new SampleDbContext();
if (ModelState.IsValid)
{
Db.Employees.Add(employee);
Db.SaveChanges();
return RedirectToAction("Index");
}
return View(employee);
}
View:
#model EmployeeList.Models.Employee
....
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
.... // controls for other properties of Employee
<div class="form-group">
#Html.LabelFor(model => model.DepartmentId, "DepartmentId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("list","select Depar")
#Html.ValidationMessageFor(model => model.DepartmentId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}

Button repeatedly calls GET method and does not POST when editing

I am trying to edit an entry in my database, but when I click submit, it just keeps calling the GET method over and over again and I cannot figure out why. I have tested this through breakpoints and there is no evidence of the POST method running - is it something to do with my Manufacturer binding?
Controller
// GET: Model/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Model model = db.Models.Find(id);
if (model == null)
{
return HttpNotFound();
}
ViewBag.Manufacturers = GetManufacturerList(model);
return View(model);
}
// POST: Model/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 EditPost(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var modelToUpdate = db.Models.Find(id);
if (TryUpdateModel(modelToUpdate, "",
new string[] { "ModelName", "ManufacturerID" }))
{
try
{
db.SaveChanges();
return RedirectToAction("Index");
}
catch (DataException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
}
ViewBag.Manufacturers = GetManufacturerList();
return View(modelToUpdate);
}
View:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Model</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ModelID)
<div class="form-group">
#Html.LabelFor(model => model.ModelName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ModelName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ModelName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Manufacturer.ManufacturerName, "Manufacturer",
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-5">
#Html.DropDownList("ManufacturerID", (List<SelectListItem>)ViewBag.Manufacturers,
htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Manufacturer.ManufacturerName, "",
new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
Models:
public class Model
{
[Required]
[Display(Name = "Manufacturer")]
[ForeignKey("Manufacturer")]
public int ManufacturerID { get; set; }
[Required]
public int ModelID { get; set; }
[Required]
[StringLength(50, ErrorMessage = "Model cannot be longer than 50 characters.")]
[RegularExpression(#"^[a-zA-Z0-9.-/() ]+$", ErrorMessage = "Invalid characters used. A-Z or a-z, 0-9, '.', '-', '()' and '/' allowed.")]
[Display(Name = "Model")]
public string ModelName { get; set; }
public virtual Manufacturer Manufacturer { get; set; }
public virtual ICollection<Item> Items { get; set; }
}
public class Manufacturer
{
[Required]
public int ManufacturerID { get; set; }
[Required]
[StringLength(50, ErrorMessage = "Manufacturer cannot be longer than 50 characters.")]
[RegularExpression(#"^[a-zA-Z0-9.-/() ]+$", ErrorMessage = "Invalid characters used. A-Z or a-z, 0-9, '.', '-', '()' and '/' allowed.")]
[Display(Name = "Manufacturer")]
public string ManufacturerName { get; set; }
public virtual ICollection<Model> Models { get; set; }
public virtual ICollection<Item> Items { get; set; }
}
Thanks in advance. Any help is greatly appreciated.
Your HttpPost method is named "EditPost". Shouldn't it be named simply "Edit" like this?
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Model model)
{
Here is a tutorial that might help you: https://www.asp.net/mvc/overview/older-versions/getting-started-with-aspnet-mvc4/examining-the-edit-methods-and-edit-view
Figured it out - I forgot to add the ActionName attribute as below:
[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public ActionResult EditPost(int? id)
{...}

Why if statement always returns false in asp.net mvc when updating data?

I used this code to update user's data in asp.net mvc 5 I think every thing is OK , but I don't know why I'm getting error message and data didn't saved and if (ModelState.IsValid) in Controller is false always .
Could anyone help me please ?
Admin Controller
[HttpGet]
public ActionResult EditUser(int id)
{
var load = db.Users.Find(id);
return View(load);
}
private const string _ImagesPathUser = "~/Images/User";
[HttpPost]
public ActionResult EditUser(User user, HttpPostedFileBase UploadImage)
{
if (ModelState.IsValid) // always returns false
{
UserRepositories blUser = new UserRepositories();
if (UploadImage != null)
{
// Delete exiting file
System.IO.File.Delete(Path.Combine(Server.MapPath(_ImagesPathUser), user.UserImage));
// Save new file
string fileName = Guid.NewGuid() + Path.GetFileName(UploadImage.FileName);
string path = Path.Combine(Server.MapPath(_ImagesPathUser), fileName);
UploadImage.SaveAs(path);
user.UserImage = fileName;
}
if (blUser.Update(user))
{
return JavaScript("alert(' added');");
}
else
{
return JavaScript("alert(' didn't add');");
}
}
else
{
return JavaScript("alert('Error');");
}
}
UserRepositories.cs
public bool Delete(int id, bool autoSave = true)
{
try
{
var entity = db.Users.Find(id);
db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
if (autoSave)
{
bool result = Convert.ToBoolean(db.SaveChanges());
if (result)
{
try
{
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\User\\" + entity.UserImage) == true)
{
File.Delete(AppDomain.CurrentDomain.BaseDirectory + "\\Images\\User\\" + entity.UserImage);
}
}
catch { }
}
return result;
}
else
return false;
}
catch
{
return false;
}
}
EditUser.cs
#model NP1.Models.User
#{
ViewBag.Title = "EditUser";
Layout = "~/Views/Admin/AdminLayout.cshtml";
}
<h2>EditUser</h2>
#using (Html.BeginForm("EditUser", "Admin", FormMethod.Post, new { enctype = "multipart/form-data", id = "myUploadForm5" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>User</h4>
<hr />
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.UserID)
<div class="form-group">
#Html.LabelFor(model => model.UserEmail, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserEmail)
#Html.ValidationMessageFor(model => model.UserEmail)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserFirstName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserFirstName)
#Html.ValidationMessageFor(model => model.UserFirstName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserLastName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserLastName)
#Html.ValidationMessageFor(model => model.UserLastName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserPassWord, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserPassWord)
#Html.ValidationMessageFor(model => model.UserPassWord)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserCellPhone, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserCellPhone)
#Html.ValidationMessageFor(model => model.UserCellPhone)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserTell, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserTell)
#Html.ValidationMessageFor(model => model.UserTell)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserImage, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.ImageFor(model => model.UserImage, new { width = "300" }, "", "Images", "User")
#Html.Upload("UploadImage")
#Html.HiddenFor(model => model.UserImage)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserAddress, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserAddress)
#Html.ValidationMessageFor(model => model.UserAddress)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserBirthDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserBirthDate)
#Html.ValidationMessageFor(model => model.UserBirthDate)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserGender, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserGender)
#Html.ValidationMessageFor(model => model.UserGender)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
User.cs
public partial class User
{
public int UserID { get; set; }
public string UserEmail { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserPassWord { get; set; }
public string UserCellPhone { get; set; }
public string UserTell { get; set; }
public string UserImage { get; set; }
public string UserAddress { get; set; }
public Nullable<byte> UserStatus { get; set; }
public Nullable<System.DateTime> UserBirthDate { get; set; }
public string UserGender { get; set; }
}
UserMetaData.cs
internal class UserMetaData
{
[ScaffoldColumn(false)]
[Bindable(false)]
public int UserID { get; set; }
[Required(ErrorMessage = "enter email", AllowEmptyStrings = false)]
[DisplayName("email")]
[Display(Name = "email")]
[RegularExpression(#"^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,4})$", ErrorMessage = "enter correct email")]
public string UserEmail { get; set; }
[Required(ErrorMessage = "enter your name", AllowEmptyStrings = false)]
[DisplayName("name")]
[Display(Name = "name")]
[StringLength(50, ErrorMessage = "should be 50")]
public string UserFirstName { get; set; }
[Required(ErrorMessage = "enter your last name", AllowEmptyStrings = false)]
[DisplayName("last name")]
[Display(Name = "last name")]
[StringLength(50, ErrorMessage = "should be 50")]
public string UserLastName { get; set; }
[Required(ErrorMessage = "enter password", AllowEmptyStrings = false)]
[Display(Name = "password")]
[DisplayName("password")]
[DataType(DataType.Password)]
public string UserPassWord { get; set; }
[Display(Name = "mobile")]
[DisplayName("mobile")]
[RegularExpression(#"^0?9[123]\d{8}$", ErrorMessage = "enter mobile correct")]
[StringLength(11, ErrorMessage = "should be 11")]
public string UserCellPhone { get; set; }
[Display(Name = "tel")]
[DisplayName("tel")]
[StringLength(11, ErrorMessage = "should be 11")]
public string UserTell { get; set; }
public string UserImage { get; set; }
public string UserAddress { get; set; }
[ScaffoldColumn(false)]
[Display(Name = "status")]
[DisplayName("status")]
public Nullable<byte> UserStatus { get; set; }
[Display(Name = "BirthDate")]
[DisplayName("BirthDate")]
public Nullable<System.DateTime> UserBirthDate { get; set; }
[Display(Name = "gender")]
[DisplayName("gender")]
public string UserGender { get; set; }
}
}
namespace NP1.Models
{
[MetadataType(typeof(NP1.Models.MetaData.UserMetaData))]
public partial class User
{
[Required(ErrorMessage = "enter your pass", AllowEmptyStrings = false)]
[Display(Name = "repeate pass")]
[DisplayName("repeate pass")]
[DataType(DataType.Password)]
[Compare("UserPassWord", ErrorMessage = "not equal")]
public string UserConfirmPassWord { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
}
For debugging purposes you can add this code to your action:
foreach (ModelState modelState in ViewData.ModelState.Values) {
foreach (ModelError error in modelState.Errors) {
//if you have some kind of logger use it here to get error data
// if not:
var e = error;
}
}
Put a break point on var e = error; line and check this error object for more info
You have few validations on each of the input elements in the model which might not be matching with database constraints.
Please debug the line ModelState.Isvalid, and use a quick watch to drilldown the errors/values details if any.
Alternatively, use below line in controller method to check for errors with model response due to input values
var errors = ModelState.Values.SelectMany(v => v.Errors);
Check if this helps you.

Get two tables data on a single MVC View

I am not so much experienced with MVC in ASP.NET. Currently working on Visual Studio 2015 Community on a demo MVC project.
I am having difficulties having two tables combined in a view.
Following are two tables of concern from few tables.
I want to show data from both the tables at the same time in a single View(HTML Page).
TABLE - COMPLAIN
CREATE TABLE [dbo].[COMPLAIN](
[JOBSHEET_NO] [int] IDENTITY(1,1) NOT NULL,
[COMPANY_NAME] [nvarchar](50) NULL,
[MODEL_NAME] [nvarchar](50) NULL,
[IMEI_SRNO] [nvarchar](50) NULL,
[BATTERY_WITH_MOBILE] [nvarchar](50) NULL,
[MEMORYCARD_WITH_MOBILE] [nvarchar](50) NULL,
[FAULT_ID] [int] NOT NULL,
[CUSTOMER_NAME] [nvarchar](50) NULL,
[CUSTOMER_MOBILE] [nvarchar](50) NULL,
[ASSIGNED_TO_TECHNICIAN] [nvarchar](50) NULL,
[REMARKS] [nvarchar](500) NULL,
[CREATE_TIMESTAMP] [datetime] NULL,
[LAST_EDIT_TIMESTAMP] [datetime] NULL,
[IN_TIMESTAMP] [datetime] NULL,
[USER_ID] [nvarchar](50) NULL,
[ESTIMATE_AMOUNT] [float] NULL,
[ESTIMATE_AMOUNT_OK_FROM_CUSTOMER] [nvarchar](50) NULL,
[OUT_TIMESTAMP] [datetime] NULL,
[JOBSHEET_COMPLETE_STATUS] [nvarchar](50) NULL,
[NARRATION] [nvarchar](500) NULL,
CONSTRAINT [PK_COMPLAIN] PRIMARY KEY CLUSTERED
(
[JOBSHEET_NO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
TABLE - REPAIRING
CREATE TABLE [dbo].[REPAIRING](
[JOBSHEET_NO] [int] NOT NULL,
[IN_TIMESTAMP] [datetime] NULL,
[CREATE_TIMESTAMP] [datetime] NULL,
[LAST_EDIT_TIMESTAMP] [datetime] NULL,
[ESTIMATE_AMOUNT] [float] NULL,
[ESTIMATE_AMOUNT_OK_FROM_CUSTOMER] [nvarchar](50) NULL,
[START_REPAIRING_TIMESTAMP] [datetime] NULL,
[END_REPAIRING_TIMESTAMP] [datetime] NULL,
[OUT_TIMESTAMP] [datetime] NULL,
[USER_ID] [nvarchar](50) NULL,
[NARRATION] [nvarchar](500) NULL,
CONSTRAINT [PK_REPAIRING] PRIMARY KEY CLUSTERED
(
[JOBSHEET_NO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[REPAIRING] WITH CHECK ADD CONSTRAINT [FK_REPAIRING_COMPLAIN] FOREIGN KEY([JOBSHEET_NO])
REFERENCES [dbo].[COMPLAIN] ([JOBSHEET_NO])
GO
ALTER TABLE [dbo].[REPAIRING] CHECK CONSTRAINT [FK_REPAIRING_COMPLAIN]
GO
I am having FK relationship between those two tables.
I would also like to know if data from both the tables can be available without any FK relationship.
Following are my models.
COMPLAIN.cs
namespace WebMSM.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
public partial class COMPLAIN
{
[Key]
[ReadOnly(true)]
[Required]
[DisplayName("JOBSHEET NO")]
public int JOBSHEET_NO { get; set; }
[Required]
[DisplayName("COMPANY NAME")]
public string COMPANY_NAME { get; set; }
[Required]
[DisplayName("MODEL NAME")]
public string MODEL_NAME { get; set; }
[Required]
[DisplayName("IMEI")]
public string IMEI_SRNO { get; set; }
[Required]
[DisplayName("BATTERY WITH MOBILE")]
public string BATTERY_WITH_MOBILE { get; set; }
[Required]
[DisplayName("MEMORY CARD WITH MOBILE")]
public string MEMORYCARD_WITH_MOBILE { get; set; }
[Required]
[DisplayName("FAULT")]
public int FAULT_ID { get; set; }
[Required]
[DisplayName("CUSTOMER NAME")]
public string CUSTOMER_NAME { get; set; }
[Required]
[DisplayName("CUSTOMER MOBILE")]
public string CUSTOMER_MOBILE { get; set; }
[Required]
[DisplayName("TECHNICIAN")]
public string ASSIGNED_TO_TECHNICIAN { get; set; }
[DisplayName("REMARKS")]
public string REMARKS { get; set; }
public Nullable<System.DateTime> CREATE_TIMESTAMP { get; set; }
public Nullable<System.DateTime> LAST_EDIT_TIMESTAMP { get; set; }
public Nullable<System.DateTime> IN_TIMESTAMP { get; set; }
[Required]
[DisplayName("USER ID")]
public string USER_ID { get; set; }
[DisplayName("ESTIMATE AMOUNT")]
public Nullable<double> ESTIMATE_AMOUNT { get; set; }
[DisplayName("ESTIMATE AMOUNT OK?")]
public string ESTIMATE_AMOUNT_OK_FROM_CUSTOMER { get; set; }
public Nullable<System.DateTime> OUT_TIMESTAMP { get; set; }
[DisplayName("STATUS")]
public string JOBSHEET_COMPLETE_STATUS { get; set; }
[Required]
[DisplayName("NARRATION")]
public string NARRATION { get; set; }
public virtual MASTER_FAULT MASTER_FAULT { get; set; }
public virtual REPAIRING REPAIRING { get; set; }
}
}
REPAIRING.cs
namespace WebMSM.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
public partial class REPAIRING
{
[Required]
[DisplayName("JOBSHEET NO")]
public int JOBSHEET_NO { get; set; }
public Nullable<System.DateTime> IN_TIMESTAMP { get; set; }
public Nullable<System.DateTime> CREATE_TIMESTAMP { get; set; }
public Nullable<System.DateTime> LAST_EDIT_TIMESTAMP { get; set; }
[Required]
[DisplayName("ESTIMATE AMOUNT")]
public Nullable<double> ESTIMATE_AMOUNT { get; set; }
[Required]
[DisplayName("ESTIMATE AMOUNT OK?")]
public string ESTIMATE_AMOUNT_OK_FROM_CUSTOMER { get; set; }
[DisplayName("START REPAIR TIME")]
public Nullable<System.DateTime> START_REPAIRING_TIMESTAMP { get; set; }
[DisplayName("END REPAIR TIME")]
public Nullable<System.DateTime> END_REPAIRING_TIMESTAMP { get; set; }
[DisplayName("OUT TIME")]
public Nullable<System.DateTime> OUT_TIMESTAMP { get; set; }
public string USER_ID { get; set; }
[DisplayName("NARRATION")]
public string NARRATION { get; set; }
public virtual COMPLAIN COMPLAIN { get; set; }
}
}
Now I have created a RepairingController which displays list of COMPLAINs on its index View.
From that View, by Clicking 'Edit' link, I would like to go to Edit view in which data from both the tables about that record should be available.
Following is RepairingController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebMSM.Models;
namespace WebMSM.Controllers
{
public class RepairingController : Controller
{
private MSMContext db = new MSMContext();
// GET: Repairing
public ActionResult Index()
{
return View(db.COMPLAINs.ToList());
}
// GET: Repairing/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
REPAIRING rEPAIRING = db.REPAIRINGs.Find(id);
if (rEPAIRING == null)
{
return HttpNotFound();
}
return View(rEPAIRING);
}
// GET: Repairing/Create
public ActionResult Create()
{
return View();
}
// POST: Repairing/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 = "JOBSHEET_NO,IN_TIMESTAMP,CREATE_TIMESTAMP,LAST_EDIT_TIMESTAMP,ESTIMATE_AMOUNT,ESTIMATE_AMOUNT_OK_FROM_CUSTOMER,START_REPAIRING_TIMESTAMP,END_REPAIRING_TIMESTAMP,OUT_TIMESTAMP,USER_ID,NARRATION")] REPAIRING rEPAIRING)
{
if (ModelState.IsValid)
{
db.REPAIRINGs.Add(rEPAIRING);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(rEPAIRING);
}
// GET: Repairing/Edit/5
public ActionResult Edit(int? id)
{
var lstOKNOTOK = new List<SelectListItem>()
{
new SelectListItem {Text="OK",Value="OK" },
new SelectListItem {Text="NOT_OK",Value="NOT_OK" },
};
ViewBag.ESTIMATE_AMOUNT_OK_FROM_CUSTOMER = lstOKNOTOK;
REPAIRING rEPAIRING = db.REPAIRINGs.Find(id);
if (rEPAIRING == null)
{
return HttpNotFound();
}
return View(rEPAIRING);
}
// POST: Repairing/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 = "JOBSHEET_NO,IN_TIMESTAMP,CREATE_TIMESTAMP,LAST_EDIT_TIMESTAMP,ESTIMATE_AMOUNT,ESTIMATE_AMOUNT_OK_FROM_CUSTOMER,START_REPAIRING_TIMESTAMP,END_REPAIRING_TIMESTAMP,OUT_TIMESTAMP,USER_ID,NARRATION")] REPAIRING rEPAIRING)
{
if (ModelState.IsValid)
{
db.Entry(rEPAIRING).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(rEPAIRING);
}
// GET: Repairing/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
REPAIRING rEPAIRING = db.REPAIRINGs.Find(id);
if (rEPAIRING == null)
{
return HttpNotFound();
}
return View(rEPAIRING);
}
// POST: Repairing/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
REPAIRING rEPAIRING = db.REPAIRINGs.Find(id);
db.REPAIRINGs.Remove(rEPAIRING);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Following is Edit.cshtml View For RepairingController.cs
#model WebMSM.Models.REPAIRING
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>REPAIRING</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.JOBSHEET_NO)
<div class="form-group">
#Html.LabelFor(model => model.JOBSHEET_NO, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-6">
#Html.TextBoxFor(model => model.JOBSHEET_NO, new { #class = "form-control" ,#readonly="readonly"} )
#Html.ValidationMessageFor(model => model.JOBSHEET_NO, "", new { #class = "text-danger" })
</div>
</div>
#*<div class="form-group">
#Html.LabelFor(model => model.IN_TIMESTAMP, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-6">
#Html.EditorFor(model => model.IN_TIMESTAMP, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.IN_TIMESTAMP, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CREATE_TIMESTAMP, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-6">
#Html.EditorFor(model => model.CREATE_TIMESTAMP, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CREATE_TIMESTAMP, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LAST_EDIT_TIMESTAMP, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-6">
#Html.EditorFor(model => model.LAST_EDIT_TIMESTAMP, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LAST_EDIT_TIMESTAMP, "", new { #class = "text-danger" })
</div>
</div>*#
<div class="form-group">
#Html.LabelFor(model => model.ESTIMATE_AMOUNT, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-6">
#Html.EditorFor(model => model.ESTIMATE_AMOUNT, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ESTIMATE_AMOUNT, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ESTIMATE_AMOUNT_OK_FROM_CUSTOMER, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-6">
#Html.DropDownListFor(model => model.ESTIMATE_AMOUNT_OK_FROM_CUSTOMER,ViewBag.ESTIMATE_AMOUNT_OK_FROM_CUSTOMER as SelectList, new { #class = "form-control" } )
#Html.ValidationMessageFor(model => model.ESTIMATE_AMOUNT_OK_FROM_CUSTOMER, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.START_REPAIRING_TIMESTAMP, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-6">
#Html.EditorFor(model => model.START_REPAIRING_TIMESTAMP, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.START_REPAIRING_TIMESTAMP, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.END_REPAIRING_TIMESTAMP, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-6">
#Html.EditorFor(model => model.END_REPAIRING_TIMESTAMP, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.END_REPAIRING_TIMESTAMP, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OUT_TIMESTAMP, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-6">
#Html.EditorFor(model => model.OUT_TIMESTAMP, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.OUT_TIMESTAMP, "", new { #class = "text-danger" })
</div>
</div>
#*<div class="form-group">
#Html.LabelFor(model => model.USER_ID, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-6">
#Html.EditorFor(model => model.USER_ID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.USER_ID, "", new { #class = "text-danger" })
</div>
</div>*#
<div class="form-group">
#Html.LabelFor(model => model.NARRATION, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-6">
#Html.EditorFor(model => model.NARRATION, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NARRATION, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-5 col-md-6">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Thanks in advance.
You should create a new view model class which has properties to represent data from both the tables
public class ComplaintDetailsVm
{
public Int JobSheetNo {set;get;}
public string CompanyName {set;get;}
public string CustomerName {set;get;}
public Decimal EsitmatedAmount {set;get;}
//Add other properties AS NEEDED
}
And use that for your view.
public ActionResult Edit(int id)
{
var vm = new ComplaintDetailsVm();
var r =db.REPAIRINGs.Find(id);
if(r!=null)
{
vm.JobSheetNo = r.JOBSHEET_NO;
vm.CustomerName= r.CUSTOMER_NAME;
//Map other properties here as needed
if(r.REPAIRING !=null)
{
vm.EstimatedAmount = r.ESTIMATED_AMOUNT;
//Map other properties here as needed
}
}
return View(vm);
}
And your view
#model ComplantDetailsVm
#using(Html.BeginForm())
{
#Html.TextBoxFor(s=>s.CompanyName)
#Html.TextBoxFor(s=>s.EstimatedAmount)
#Html.HiddenFor(s=>s.JobSheetNo)
<input type="submit" />
}
So when user posts the form, we need to read the data from our viewmodel object and use that for saving
[HttpPost]
public ActionResult Edit(ComplantDetailVm model)
{
if(ModelState.IsValid)
{
var e=db.COMPLAINs.FirstOrDefault(s=>s.JOBSHEET_NO==model.JobSheetNo);
if(e!=null)
{
// Update the property values
e.CompanyName = model.CompanyName;
//Map other properties also
db.Entry(e).State = EntityState.Modified;
db.SaveChanges();
//to do : Redirect to Success message page.
}
}
return View(model);
}

Issue extending the base EDMX model and calling the functions in the data model

I am writing a solution using MVC with scaffolding. It uses Entity Framework v6 and is database first in design. The base data model (ServiceAccountFilter) is extended by the data model (FilterModel). There is some logic in the FilterModel but the properties are all inherited from the base model. It seems as though the controller insists on using the base model. When I change the return to use the FilterModel, I get an error that the view requires the base model and then the functions in the FilterModel are not visible in the views? Not sure how to handle this?
Base Model:
namespace FHN.ARX.AdminWeb
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
public partial class ServiceAccountFilter
{
[DisplayName("Filter ID")]
public virtual int FilterId { get; set; }
[DisplayName("Filter Name")]
public virtual string FilterName { get; set; }
[DisplayName("Service Account")]
public virtual string ServiceAccount { get; set; }
[DisplayName("Doc Type")]
public virtual string DocType { get; set; }
[DisplayName("Doc Type ID")]
public virtual Nullable<int> DocTypeId { get; set; }
[DisplayName("Doc Name ID")]
public virtual string DocNameId { get; set; }
[DisplayName("Last Modified By ID")]
public virtual string LastModifiedById { get; set; }
[DisplayName("Last Modified By")]
public virtual string LastModifiedByName { get; set; }
[DisplayName("Last Modified")]
public virtual Nullable<System.DateTime> LastModified { get; set; }
[DisplayName("Months To Return")]
public virtual Nullable<int> MonthsToReturn { get; set; }
}
}
FilterModel
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FHN.ARX.AdminWeb.Models
{
public class FilterModel : ServiceAccountFilter
{
[DisplayName("Filter ID")]
public override int FilterId { get; set; }
[DisplayName("Filter Name")]
public override string FilterName { get; set; }
[DisplayName("Service Account")]
public override string ServiceAccount { get; set; }
[DisplayName("Doc Type")]
public override string DocType { get; set; }
[DisplayName("Doc Type ID")]
public override Nullable<int> DocTypeId { get; set; }
[DisplayName("Doc Name ID")]
public override string DocNameId { get; set; }
[DisplayName("Last Modified By ID")]
public override string LastModifiedById { get; set; }
[DisplayName("Last Modified By")]
public override string LastModifiedByName { get; set; }
[DisplayName("Last Modified")]
public override Nullable<System.DateTime> LastModified { get; set; }
[DisplayName("Months To Return")]
public override Nullable<int> MonthsToReturn { get; set; }
public bool Selected { get; set; }
public string Checkboxes { get; set; }
public IEnumerable<SelectListItem> DocTypesList(string id)
{
using (var db = new ARXEntities())
{
var docType = new List<SelectListItem>();
docType = (from t in db.vwMapDocNamesToSecurityUsers
where t.UserDN == id
orderby t.DocType
select new { t.DocType, t.DocTypeId }).Distinct().Select(x => new SelectListItem() { Text = x.DocType, Value = x.DocTypeId.ToString() }).OrderBy(x => x.Text).ToList();
return docType;
}
}
public IEnumerable<SelectListItem> DocNamesList()
{
using (var db = new ARXEntities())
{
IEnumerable<SelectListItem> docName = new List<SelectListItem>();
var loggedInUser = "C2693"; // HttpContext.Current.User.Identity.Name.Split('\\')[1];
docName = (from t in db.vwMapDocNamesToSecurityUsers
where t.UserDN == loggedInUser
select new { t.DocName, t.DocNameId, t.DocTypeId }).Distinct().Select(x => new SelectListItem()
{
Text = x.DocName,
Value = x.DocNameId.ToString(),
Group = new SelectListGroup() { Name = x.DocTypeId.ToString() }
}).Distinct().OrderBy(x => x.Text).ToList();
var docCount = docName.Count();
return docName;
}
}
public IEnumerable<SelectListItem> ServiceAccountList()
{
using (var db = new ARXEntities())
{
var sa = new List<SelectListItem>();
sa = (from t in db.vwMapDocNamesToSecurityUsers
where t.UserDN.StartsWith("sa_")
orderby t.UserDN
select new { t.UserDN }).Distinct().Select(x => new SelectListItem() { Text = x.UserDN, Value = x.UserDN }).OrderBy(x => x.Text).ToList();
return sa;
}
}
public IEnumerable<SelectListItem> DocNamesByDocTypeIdList()
{
using (var db = new ARXEntities())
{
IEnumerable<SelectListItem> docName = new List<SelectListItem>();
docName = (from t in db.vwMapDocNamesToSecurityUsers
select new { t.DocName, t.DocNameId, t.DocTypeId }).Distinct().Select(x => new SelectListItem()
{
Text = x.DocName,
Value = x.DocNameId.ToString(),
Group = new SelectListGroup() { Name = x.DocTypeId.ToString() }
}).Distinct().OrderBy(x => x.Text).ToList();
var docCount = docName.Count();
return docName;
}
}
public IEnumerable<SelectListItem> GetDocNamesForFilterId(int? id)
{
using (var db = new ARXEntities())
{
IEnumerable<SelectListItem> docName = new List<SelectListItem>();
docName = (from t in db.ServiceAccountFilters
where t.FilterId == id
select new { t.DocNameId, t.FilterId }).Distinct().Select(x => new SelectListItem()
{
Text = x.DocNameId,
Value = x.DocNameId.ToString(),
Group = new SelectListGroup() { Name = x.DocNameId.ToString() }
}).Distinct().OrderBy(x => x.Text).ToList();
return docName;
}
}
}
}
Controller Edit Action
public ActionResult Edit(int? id)
{
if (id == null)
{
var saf = new FilterModel();
return View(saf);
}
FilterModel serviceAccountFilter = (FilterModel)db.ServiceAccountFilters.Find(id); <----Tried casting here, but still didnt work.
if (serviceAccountFilter == null)
{
return HttpNotFound();
}
return View(serviceAccountFilter);
}
Edit View
#model FHN.ARX.AdminWeb.Models.FilterModel
#{
ViewBag.Title = "Edit A Filter";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="pageTitle">Filter Maintenance</div>
#using (Html.BeginForm(new { id = "filterForm" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.FilterId)
#Html.HiddenFor(model => model.LastModified)
#Html.HiddenFor(model => model.LastModifiedById)
#Html.HiddenFor(model => model.LastModifiedByName)
<div class="ddlGroups, btmMarg-15">
#Html.DropDownListFor(m => m.ServiceAccount, Model.ServiceAccountList(), "Select a Service Account")
</div>
<div class="ddlGroups, col-md-10, btmMarg-15">
#Html.LabelFor(model => model.ServiceAccount, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.ServiceAccount, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="ddlGroups, col-md-10, btmMarg-15">
#Html.LabelFor(model => model.DocTypeId, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.DocTypeId, new { htmlAttributes = new { #class = "form-control" } })
</div>
<p class="leftMarg-15 text-default" id="docNamesHdrText">Select the document names to be included in the filter.</p>
<div class="ckDocNames">
#foreach (var dn in Model.DocNamesByDocTypeIdList())
{
<div class="checkboxContainer">
<input class="ckBoxes" type="checkbox" name="DocNameId" value="#dn.Value" dtid="#dn.Group.Name" />#dn.Text<br />
</div>
}
</div>
<div class="form-group, col-md-10, btmMarg-15" id="monthsGroup">
#Html.LabelFor(model => model.MonthsToReturn, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.MonthsToReturn, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MonthsToReturn, "", new { #class = "text-danger" })
</div>
<div class="form-group, col-md-10, btmMarg-15" id="filterNameGroup">
#Html.LabelFor(model => model.FilterName, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.FilterName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FilterName, "", new { #class = "text-danger" })
</div>
<br />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" id="modSaveButton" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "ActiveFilters") |
#Html.ActionLink("Admin Home", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
this is an example of using a viewmodel on your case ... (may be it's not prefect but just a hint on your way)
namespace FHN.ARX.AdminWeb
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
public partial class ServiceAccountFilter
{
public int FilterId { get; set; }
public string FilterName { get; set; }
public string ServiceAccount { get; set; }
public string DocType { get; set; }
public Nullable<int> DocTypeId { get; set; }
public string DocNameId { get; set; }
public string LastModifiedById { get; set; }
public string LastModifiedByName { get; set; }
public Nullable<System.DateTime> LastModified { get; set; }
public Nullable<int> MonthsToReturn { get; set; }
}
}
no need for the filter model now and instead of that put all the logic in the controller under a heper region
#region Helpers
public IEnumerable<SelectListItem> DocTypesList(string id)
{
using (var db = new ARXEntities())
{
var docType = new List<SelectListItem>();
docType = (from t in db.vwMapDocNamesToSecurityUsers
where t.UserDN == id
orderby t.DocType
select new { t.DocType, t.DocTypeId }).Distinct().Select(x => new SelectListItem() { Text = x.DocType, Value = x.DocTypeId.ToString() }).OrderBy(x => x.Text).ToList();
return docType;
}
}
public IEnumerable<SelectListItem> DocNamesList()
{
using (var db = new ARXEntities())
{
IEnumerable<SelectListItem> docName = new List<SelectListItem>();
var loggedInUser = "C2693"; // HttpContext.Current.User.Identity.Name.Split('\\')[1];
docName = (from t in db.vwMapDocNamesToSecurityUsers
where t.UserDN == loggedInUser
select new { t.DocName, t.DocNameId, t.DocTypeId }).Distinct().Select(x => new SelectListItem()
{
Text = x.DocName,
Value = x.DocNameId.ToString(),
Group = new SelectListGroup() { Name = x.DocTypeId.ToString() }
}).Distinct().OrderBy(x => x.Text).ToList();
var docCount = docName.Count();
return docName;
}
}
public IEnumerable<SelectListItem> ServiceAccountList()
{
using (var db = new ARXEntities())
{
var sa = new List<SelectListItem>();
sa = (from t in db.vwMapDocNamesToSecurityUsers
where t.UserDN.StartsWith("sa_")
orderby t.UserDN
select new { t.UserDN }).Distinct().Select(x => new SelectListItem() { Text = x.UserDN, Value = x.UserDN }).OrderBy(x => x.Text).ToList();
return sa;
}
}
public IEnumerable<SelectListItem> DocNamesByDocTypeIdList()
{
using (var db = new ARXEntities())
{
IEnumerable<SelectListItem> docName = new List<SelectListItem>();
docName = (from t in db.vwMapDocNamesToSecurityUsers
select new { t.DocName, t.DocNameId, t.DocTypeId }).Distinct().Select(x => new SelectListItem()
{
Text = x.DocName,
Value = x.DocNameId.ToString(),
Group = new SelectListGroup() { Name = x.DocTypeId.ToString() }
}).Distinct().OrderBy(x => x.Text).ToList();
var docCount = docName.Count();
return docName;
}
}
public IEnumerable<SelectListItem> GetDocNamesForFilterId(int? id)
{
using (var db = new ARXEntities())
{
IEnumerable<SelectListItem> docName = new List<SelectListItem>();
docName = (from t in db.ServiceAccountFilters
where t.FilterId == id
select new { t.DocNameId, t.FilterId }).Distinct().Select(x => new SelectListItem()
{
Text = x.DocNameId,
Value = x.DocNameId.ToString(),
Group = new SelectListGroup() { Name = x.DocNameId.ToString() }
}).Distinct().OrderBy(x => x.Text).ToList();
return docName;
}
}
#endregion
in your controller Edit Action
public ActionResult Edit(int? id)
{
if (id == null)
{
var saf = new FilterModel();
return View(saf);
}
var serviceAccountFilter = db.ServiceAccountFilters.Find(id)
if (serviceAccountFilter == null)
{
return HttpNotFound();
}
var model = new FilterViewModel
{
FilterId = serviceAccountFilter.FilterId,
FilterName = serviceAccountFilter.FilterName,
ServiceAccount = serviceAccountFilter.ServiceAccount,
DocType = serviceAccountFilter.DocType,
DocTypeId = serviceAccountFilter.DocTypeId,
DocNameId = serviceAccountFilter.DocNameId,
LastModifiedById = serviceAccountFilter.LastModifiedById,
LastModifiedByName = serviceAccountFilter.LastModifiedByName,
LastModified = serviceAccountFilter.LastModified,
MonthsToReturn = serviceAccountFilter.MonthsToReturn,
ServiceAccountList = ServiceAccountList(),
DocNamesByDocTypeIdList = DocNamesByDocTypeIdList()
};
return View(model);
}
and here is a ViewModel lets say it's name will be FilterViewModel
public class FilterModel
{
[DisplayName("Filter ID")]
public int FilterId { get; set; }
[DisplayName("Filter Name")]
public string FilterName { get; set; }
[DisplayName("Service Account")]
public string ServiceAccount { get; set; }
[DisplayName("Doc Type")]
public string DocType { get; set; }
[DisplayName("Doc Type ID")]
public Nullable<int> DocTypeId { get; set; }
[DisplayName("Doc Name ID")]
public string DocNameId { get; set; }
[DisplayName("Last Modified By ID")]
public string LastModifiedById { get; set; }
[DisplayName("Last Modified By")]
public string LastModifiedByName { get; set; }
[DisplayName("Last Modified")]
public Nullable<System.DateTime> LastModified { get; set; }
[DisplayName("Months To Return")]
public Nullable<int> MonthsToReturn { get; set; }
public IEnumerable<SelectListItem> ServiceAccountList { get; set; }
public IEnumerable<SelectListItem> DocNamesByDocTypeIdList { get; set; }
}
and then your Edit View will be
#model FilterViewModel // check the name space
#{
ViewBag.Title = "Edit A Filter";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="pageTitle">Filter Maintenance</div>
#using (Html.BeginForm(new { id = "filterForm" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.FilterId)
#Html.HiddenFor(model => model.LastModified)
#Html.HiddenFor(model => model.LastModifiedById)
#Html.HiddenFor(model => model.LastModifiedByName)
<div class="ddlGroups, btmMarg-15">
#Html.DropDownListFor(m => m.ServiceAccount, Model.ServiceAccountList(), "Select a Service Account")
</div>
<div class="ddlGroups, col-md-10, btmMarg-15">
#Html.LabelFor(model => model.ServiceAccount, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.ServiceAccount, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="ddlGroups, col-md-10, btmMarg-15">
#Html.LabelFor(model => model.DocTypeId, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.DocTypeId, new { htmlAttributes = new { #class = "form-control" } })
</div>
<p class="leftMarg-15 text-default" id="docNamesHdrText">Select the document names to be included in the filter.</p>
<div class="ckDocNames">
#foreach (var dn in Model.DocNamesByDocTypeIdList())
{
<div class="checkboxContainer">
<input class="ckBoxes" type="checkbox" name="DocNameId" value="#dn.Value" dtid="#dn.Group.Name" />#dn.Text<br />
</div>
}
</div>
<div class="form-group, col-md-10, btmMarg-15" id="monthsGroup">
#Html.LabelFor(model => model.MonthsToReturn, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.MonthsToReturn, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MonthsToReturn, "", new { #class = "text-danger" })
</div>
<div class="form-group, col-md-10, btmMarg-15" id="filterNameGroup">
#Html.LabelFor(model => model.FilterName, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.FilterName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FilterName, "", new { #class = "text-danger" })
</div>
<br />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" id="modSaveButton" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "ActiveFilters") |
#Html.ActionLink("Admin Home", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}

Resources