MVC Dropdown list from a froma different Model - c#

I'm trying to create a dropdown on my View that populates all the usernames specified in a different table.
I've tried the tuple route but it doesn't seem to be working for me.
Also looked into adding a model containing both models (Users and Tasks)
View
#model Tuple<Task,User>
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Task</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Item1.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Item1.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Item1.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Item1.Details, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Item1.Details, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Item1.Details, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Item1.StartDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Item1.StartDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Item1.StartDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Item1.EndDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Item1.EndDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Item1.EndDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Item1.AssignedTo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor()
#Html.ValidationMessageFor(model => model.Item1.AssignedTo, "", 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>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Controller
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 Base.Models;
using PagedList;
namespace Base.Controllers
{
public class UsersController : Controller {
private WebDBEntities db = new WebDBEntities();
// GET: Users
public ActionResult Index(string sortOrder,string currentFilter, string searchString,int? page) {
ViewBag.NameSortParam = string.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewBag.SurnameSortParam = sortOrder == "Surname" ? "surname_desc" : "Surname";
ViewBag.TeamSortParam = sortOrder == "Team" ? "team_desc" : "Team";
if(searchString != null) {
page = 1;
} else {
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var users = from u in db.Users select u;
if (!string.IsNullOrEmpty(searchString)) {
users = users.Where(u => u.Name.Contains(searchString) || u.Surname.Contains(searchString));
}
switch (sortOrder) {
case "name_desc":
users = users.OrderByDescending(u => u.Name);
break;
case "Team":
users = users.OrderBy(u => u.Team);
break;
case "team_desc":
users = users.OrderByDescending(u => u.Team);
break;
case "Surname":
users = users.OrderBy(u => u.Surname);
break;
case "surname_desc":
users = users.OrderByDescending(u => u.Surname);
break;
default:
users = users.OrderBy(u => u.Name);
break;
}
int pageSize = 10;
int pageNumber = (page ?? 1);
return View(users.ToPagedList(pageNumber,pageSize));
}
// GET: Users/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
User user = db.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(user);
}
// GET: Users/Create
public ActionResult Create()
{
return View();
}
// POST: Users/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 = "ID,Name,Surname,Team,UserName")] User user)
{
if (ModelState.IsValid)
{
user.UserName = string.Format("{0}{1}", user.Name.Substring(0, 1), user.Surname);
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
// GET: Users/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
User user = db.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(user);
}
// POST: Users/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 = "ID,Name,Surname,Team,UserName")] User user)
{
if (ModelState.IsValid)
{
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
// GET: Users/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
User user = db.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(user);
}
// POST: Users/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
User user = db.Users.Find(id);
db.Users.Remove(user);
db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult ViewUserTasks(string Username) {
return View("UserTasks",db.Tasks.Where(uu => uu.AssignedTo == Username));
}
public ActionResult GetAllUsers() {
List<string> users = new List<string>();
foreach (var item in db.Users) {
users.Add(item.UserName.ToString())
}
return View(users);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Any assistance would be great, thanks in advance.

Related

asp.net web application hide data field at the backend

I am making a web application and I used entity based EF designer from database model I want to hide modified by and modified Date for the backend and it shouldn't display to the user Can someone help how do I make this work? I have attached my picture and code below please let me know if there is any question.
Picture:
Controller CODE:
// GET: Contract
public ActionResult Index()
{
return View(db.Contracts.ToList());
}
// GET: Contract/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Contract contract = db.Contracts.Find(id);
if (contract == null)
{
return HttpNotFound();
}
return View(contract);
}
// GET: Contract/Create
public ActionResult Create()
{
return View();
}
// POST: Contract/Create
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
\[HttpPost\]
\[ValidateAntiForgeryToken\]
public ActionResult Create(\[Bind(Include = "Id,ContractName,ContractNumber,CreatedBy,CreatedDate,ModifiedBy,ModifiedDate")\] Contract contract)
{
if (ModelState.IsValid)
{
db.Contracts.Add(contract);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(contract);
}
// GET: Contract/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Contract contract = db.Contracts.Find(id);
if (contract == null)
{
return HttpNotFound();
}
return View(contract);
}
// POST: Contract/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
\[HttpPost\]
\[ValidateAntiForgeryToken\]
public ActionResult Edit(\[Bind(Include = "Id,ContractName,ContractNumber,CreatedBy,CreatedDate,ModifiedBy,ModifiedDate")\] Contract contract)
{
if (ModelState.IsValid)
{
db.Entry(contract).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(contract);
}
// GET: Contract/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Contract contract = db.Contracts.Find(id);
if (contract == null)
{
return HttpNotFound();
}
return View(contract);
}
// POST: Contract/Delete/5
\[HttpPost, ActionName("Delete")\]
\[ValidateAntiForgeryToken\]
public ActionResult DeleteConfirmed(int id)
{
Contract contract = db.Contracts.Find(id);
db.Contracts.Remove(contract);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
`
I tried to figure out but I don't know how to hide these two modified date and modified by at the backend.
View code
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Contract</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ContractName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ContractName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ContractName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContractNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ContractNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ContractNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreatedBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CreatedBy, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CreatedBy, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreatedDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CreatedDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CreatedDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ModifiedBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ModifiedBy, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ModifiedBy, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ModifiedDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ModifiedDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ModifiedDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button style="background-color:white; border-color:darkgrey;"><input type="submit" value="Create" class="btn btn-default" /></button>
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Often times the entity types stored in the database have fields you don't want to, can't, or shouldn't expose on the UI.
If you're not concerned about the data being present and would just like to "hide" it, simply don't include those in the table markup.
If however you don't want the fields present at all, a common way to get around that is to create a DTO class that only has the fields you wish to expose. Update your UI to target the DTO and remove the columns from the table.
public class ContractDto
{
// all the fields you want to expose
// Ctor
public ContractorDto(Contract contract) { ... }
// "From" pattern
public static ContractDto From(Contract contract)
=> new ContractDto { ... }
// An implicit operator can also be helpful
public static implicit operator ContractDto(Contract contract)
=> new ContractDto { ... }
}
If you need to update the fields you dropped after an update for example, load the entity type using the primary key and update it. This assumes you have some way to populate the current user.
var entity = db.Contracts.Find(contractDto.Id);
// update entity from dto as needed
entity.ModifiedBy = // populate the user from context or similar
entity.ModifiedDate = DateTime.Now;

Map two entities from one table in ASP.NET

I am working on a library management website. As user of the application, I want to be able to create new employees, for example ceo, manager and regular employee. I have done that and it is working.
But I want to be able to the employees to manage each other depending on their role, for example I want the:
CEO to manage managers but not employees
Managers to manage other managers and employees
No one can manage the CEO
To do that I have tried to map managerID against the id of the employee (I don't know if its a good idea):
public partial class Employees
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] // For autoincrement
//public int EmployeeId { get; set; }
//[Required]
//[Index]
//public int TheManagerId { get; set; } // Manager ID Foreign Key
//[Required]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Nullable<decimal> Salary { get; set; }
public Nullable<bool> IsCEO { get; set; }
public Nullable<bool> IsManager { get; set; }
public Nullable<int> ManagerId { get; set; }
}
And this is how my Create.cshtml looks like:
#model LibraryProject.Employees
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employees</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Salary, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Salary, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Salary, "Your input should be an integer between 1-10.", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IsCEO, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.IsCEO)
#Html.ValidationMessageFor(model => model.IsCEO, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IsManager, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.IsManager)
#Html.ValidationMessageFor(model => model.IsManager, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ManagerId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ManagerId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ManagerId, "", 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>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
#using (Html.BeginForm())
{
if (!string.IsNullOrEmpty(ViewBag.ErrorMessage5))
{
<div>
<p>
<span style="color:red;">#ViewBag.ErrorMessage5</span>
</p>
</div>
}
<div class="form-horizontal" />
}
And this is how my Employee controller looks like:
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 LibraryProject;
namespace LibraryProject.Controllers
{
public class EmployeesController : Controller
{
private LibraryDbEntities db = new LibraryDbEntities();
// GET: Employees
public ActionResult Index()
{
// Linq queries to show all the employees separately, is used to not mixed them up.
var getCeo = from employeCEO in db.Employees
where employeCEO.IsCEO == true
select employeCEO;
var getEmployee = from employee in db.Employees
where employee.IsCEO == false && employee.IsManager == false
select employee;
var getManager = from employeeManager in db.Employees
where employeeManager.IsManager == true && employeeManager.IsCEO == false
select employeeManager;
IEnumerable<Employees> list = getCeo.Concat(getEmployee).Concat(getManager);
return View(list.ToList());
}
public ActionResult CEO()
{
// linq query used to display ceo in a separate view
var getCeo = from employeCEO in db.Employees
where employeCEO.IsCEO == true
select employeCEO;
return View(getCeo);
}
public ActionResult TheManager()
{
// linq query used to display manager in a separate view
var getManager = from employeeManager in db.Employees
where employeeManager.IsManager == true && employeeManager.IsCEO == false
select employeeManager;
return View(getManager);
}
public ActionResult RegularEmployee()
{
// linq query used to display employee in a separate view
var getEmployee = from employee in db.Employees
where employee.IsCEO == false && employee.IsManager == false
select employee;
return View(getEmployee);
}
// GET: Employees/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Employees employees = db.Employees.Find(id);
if (employees == null)
{
return HttpNotFound();
}
return View(employees);
}
// GET: Employees/Create
public ActionResult Create()
{
ViewBag.Employees = new SelectList(db.Category, "Id", "Employees");
return View();
}
// POST: Employees/Create
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,FirstName,LastName,Salary,IsCEO,IsManager,ManagerId")] Employees employees)
{
if (ModelState.IsValid)
{
//salary coefficient for the employees
decimal salaryCeo = 2.725M;
decimal salaryManager = 1.725M;
decimal employeeSalary = 1.125M;
var ceo = db.Employees.Count(x => x.IsCEO == true);
//Checks if there is a ceo
if (ceo == 0)
{
employees.Salary = employees.Salary * salaryCeo; // calculate ceo salary
db.Employees.Add(employees);
db.SaveChanges();
return RedirectToAction("Index");
}
else if (ceo == 1 && employees.IsCEO == true) // check if there is a ceo, if yes show errormessage
{
ViewBag.ErrorMessage5 = "There is already a CEO in the database! You cannot create a second one!";
}
else if(employees.IsCEO == false && employees.IsManager == false) // check if the employee is ceo or manager, if false its a regular employee
{
employees.Salary = employees.Salary * employeeSalary; // calculate regular employees salary
db.Employees.Add(employees);
db.SaveChanges();
return RedirectToAction("Index");
}
else if (employees.IsCEO == false && employees.IsManager == true) // manager
{
employees.Salary = employees.Salary * salaryManager; // manager salary
db.Employees.Add(employees);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View(employees);
}
// GET: Employees/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Employees employees = db.Employees.Find(id);
if (employees == null)
{
return HttpNotFound();
}
return View(employees);
}
// POST: Employees/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,FirstName,LastName,Salary,IsCEO,IsManager,ManagerId")] Employees employees)
{
if (ModelState.IsValid)
{
db.Entry(employees).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(employees);
}
// GET: Employees/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Employees employees = db.Employees.Find(id);
if (employees == null)
{
return HttpNotFound();
}
return View(employees);
}
// POST: Employees/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Employees employees = db.Employees.Find(id);
db.Employees.Remove(employees);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
I KNOW IT IS SOME CODE THERE... BUT I HOPE SOMEONE IS OUT THERE TO HELP.
THANKS.
But I want to be able to the employees to manage each other depending on their role, for example I want the:
CEO to manage managers but not employees
Managers to manage other
managers and employees No one can manage the CEO
I think what you want to achieve is Authorize, not the relationship in table.
For how to Customize a Authorize Attribute, You can refer to this thread.

ASP.NET MVC 5 DropDownList from another model

I'm just getting started with MVC. I'm building a project in asp.net mcv 5 using entity framework. I have researched many threads but I didn't find anything that would help solve my problem. I have two models:
Resource:
public class Resource
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Comments { get; set; }
[Required]
public ResourceType Type { get; set; }
public bool IsActive { get; set; }
}
ResourceType:
public class ResourceType
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
And the problem is: In View > Resource > Create I want to add DropDownList for object ResourceType Type with values from class ResourceType string Name
Create.cshtml:
#model NetAudit.Models.Resource
#{
ViewBag.Title = "Create Resource";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Resource</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>
<div class="form-group">
#Html.LabelFor(model => model.Comments, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Comments, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Comments, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
HERE
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IsActive, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.IsActive)
#Html.ValidationMessageFor(model => model.IsActive, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Dodaj" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to list", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
RecourceType controller:
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using NetAudit.Models;
namespace NetAudit.Controllers
{
public class ResourceTypesController : BaseController
{
private readonly ApplicationDbContext _db = new ApplicationDbContext();
[Authorize]
public ActionResult Index()
{
return View(_db.ResourceTypes.ToList());
}
[Authorize]
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var resourceType = _db.ResourceTypes.Find(id);
if (resourceType == null)
{
return HttpNotFound();
}
return View(resourceType);
}
[Authorize]
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ResourceType resourceType)
{
if (ModelState.IsValid)
{
_db.ResourceTypes.Add(resourceType);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(resourceType);
}
[Authorize]
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var resourceType = _db.ResourceTypes.Find(id);
if (resourceType == null)
{
return HttpNotFound();
}
return View(resourceType);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ResourceType resourceType)
{
if (ModelState.IsValid)
{
_db.Entry(resourceType).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(resourceType);
}
[Authorize]
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var resourceType = _db.ResourceTypes.Find(id);
if (resourceType == null)
{
return HttpNotFound();
}
return View(resourceType);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
var resourceType = _db.ResourceTypes.Find(id);
if (resourceType == null)
{
return HttpNotFound();
}
_db.ResourceTypes.Remove(resourceType);
_db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
}
Resource controller:
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using NetAudit.Models;
namespace NetAudit.Controllers
{
public class ResourceTypesController : BaseController
{
private readonly ApplicationDbContext _db = new ApplicationDbContext();
[Authorize]
public ActionResult Index()
{
return View(_db.ResourceTypes.ToList());
}
[Authorize]
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var resourceType = _db.ResourceTypes.Find(id);
if (resourceType == null)
{
return HttpNotFound();
}
return View(resourceType);
}
[Authorize]
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ResourceType resourceType)
{
if (ModelState.IsValid)
{
_db.ResourceTypes.Add(resourceType);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(resourceType);
}
[Authorize]
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var resourceType = _db.ResourceTypes.Find(id);
if (resourceType == null)
{
return HttpNotFound();
}
return View(resourceType);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ResourceType resourceType)
{
if (ModelState.IsValid)
{
_db.Entry(resourceType).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(resourceType);
}
[Authorize]
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var resourceType = _db.ResourceTypes.Find(id);
if (resourceType == null)
{
return HttpNotFound();
}
return View(resourceType);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
var resourceType = _db.ResourceTypes.Find(id);
if (resourceType == null)
{
return HttpNotFound();
}
_db.ResourceTypes.Remove(resourceType);
_db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
}
I spent a lot of time looking for a solution to this problem. I would appreciate your feedback on this.
I think the best way to get what you want is to create a ViewModel, this allows you create a view with various classes.
Under your solution create a new folder named ViewModels. Create a new class and name it CreateResourceViewModel.
public class CreateResourceViewModel
{
public Resource Resource {get;set;}
public SelectList ResourceType {get;set;} //this will create the list of resourcetypes
public int IdResourceType {get;set;} //this will be used to select the id of resourceType you are selecting.
public CreateResourceViewModel (Resource resource,List<ResourceType>resourceType) //create a constructor
{
this.Resource = resource;
//here you will set the list as a new selectList, stating where the list will come from. the Id de valuevaluefield, and the name is the valuetextfield
this.ResourceType= new SelectList(resourceType,"Id","Name");
}
public CreateResourceViewModel(){} //you need this second constructor
}
Now you need a Create ActionResult that accepts a ViewModel in your resource Controller
// GET: Locals/Create
public ActionResult Create()
{
Resource resource = new Resource();
List<ResourceType> resourceType;
using (yourcontext db = new yourcontext())
{
resourceType = db.ResourceType.ToList(); //fill your list with the resourceTypes that are in your database
}
CreateResourceViewModel vm = new CreateResourceViewModel(resource,resourceType); //create a new viewmodel and give it the parameters necesary that we created
return View(vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CreateResourceViewModel vm)
{
using (yourcontext db = new yourcontext())
{
if (ModelState.IsValid)
{
try {
vm.Resource.Type = db.ResourceTpe.Find(vm.IdResourceType); //using the ID selected in the view find it in the database
db.Resources.Add(vm.Resource);
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception e)
{
e.Message();
}
}
return View(vm);
}
}
Now onto the view for the ViewModel
#model yourSolution.ViewModels.CreateResourceViewModel
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Resource</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>
<div class="form-group">
#Html.LabelFor(model => model.Comments, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Comments, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Comments, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ResourceType, htmlAttributes: new { #class = "control-label col-md-2" })
//this is what you need to create a dropdownlist with all the resourceTypes
<div class="col-md-10">
#Html.DropDownListFor(model => model.IdResourceType, Model.ResourceType,"--Select--" )
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IsActive, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.IsActive)
#Html.ValidationMessageFor(model => model.IsActive, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Dodaj" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to list", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Hope this helps!!
First of you have a mistake to put Resource Controller here (both of Resource and ResourceType are ResourceType). fix it first.
Put in the Here section this code to render a select element from ViewBag.Types:
#Html.DropDownListFor(m => m.Type.Id, (SelectList)ViewBag.Types, new
{
#class = "form-control"
});
Before it you must fill ViewBag.Types in the action, Change the first Create action of ResourceController to this:
[Authorize]
public ActionResult Create()
{
ViewBag.Types = new SelectList(_db.ResourceTypes.ToList(), "Id", "Name", "0");
return View();
}
It will be worked.

Kendo ASP.NET MVC : Assigning differing functionality to buttons on a grid

Java back-end guy thrown into .net fullstack(MVC, EF, Kendo, etc...) seeks help with assigning differing functionality to buttons on a grid(Kendo).
What I am trying to accomplish: Create custom/differing behaviors for 3 buttons.
On my Index page/view, I have 3 buttons: Create, Edit, Delete.
Create should direct the user to a new page/view: /Dies/Create
Edit should direct the user to a new page/view: /Dies/Edit
Delete should produce a popup window prompting the user with the standard
Question: Could you provide me with an elegant solution to my goals(proposed above)?
Note: As you'll see in my Index page/view, I've started attempting to implement a solution via the use of command.Custom & some js functions(located at the bottom of the file). But I don't have enough understand to feel confident about what I'm doing.
Note: I've included views below. Like wise, I have included my controller, logic, profile(mapping), & model for additional context.
My pages/views:
Index.cshtml
#model IEnumerable<LabelArchive.Models.Die.DieModel>
#{
ViewBag.Title = "Manage Die";
}
<h2>Die Management</h2>
#(Html.Kendo().Grid<LabelArchive.Models.Die.DieModel>()
.Name("diesgrid")
.Columns(columns =>
{
columns.Bound(i => i.Name);
columns.Bound(i => i.Width);
columns.Bound(i => i.Height);
columns.Bound(i => i.DieShapeName);
columns.Bound(i => i.DieTypeName);
columns.Command(command =>
{
command.Custom("Edit").Click("editDie");
command.Custom("Delete").Click("deleteDie");
}).Width(250);
})
.ToolBar(toolbar => toolbar.Custom().Text("Create").Action("Create", "Dies"))
.Pageable()
.Sortable()
.Scrollable()
.HtmlAttributes(new { style = "height:550px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Events(events => events.Error("error_handler"))
.Model(model => model.Id(i => i.DieId))
.Read(read => read.Action("Die_Read", "Dies"))
.Destroy(destroy => destroy.Action("Die_Delete", "Dies"))
)
)
#*<script src="~/ViewScripts/kendo_generic.js"></script>*#
<script type="text/javascript">
// error_handler
function error_handler(e) {
if (e.errors) {
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function() {
message += this + "\n";
});
}
});
alert(message);
}
}
// createDie
function createDie(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest('tr'));
document.location.href = '#(Url.Action("Create", "Dies"))';
}
// editDie
function editDie(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest('tr'));
document.location.href = '#(Url.Action("Edit", "Dies"))' + '/' + dataItem.DieId.toString();
}
// deleteDie
function deleteDie(e) {
}
</script>
Create.cshtml
#model LabelArchive.Models.Die.DieModel
#{
ViewBag.Title = "Create Die";
}
<h2>Create Die</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>DieModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.Partial("_CreateOrEdit", Model)
<!--submit/create-->
<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>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Edit.cshtml
#model LabelArchive.Models.Die.DieModel
#{
ViewBag.Title = "Edit Die";
}
<h2>Edit Die</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>DieModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.DieId)
#Html.Partial("_CreateOrEdit", Model)
<!--submit/save-->
<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>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
_CreateOrEdit.cshtml (a partial view)
#using LabelArchive.Models.DieShape
#model LabelArchive.Models.Die.DieModel
<!--CompanyId-->
<div class="form-group">
#Html.HiddenFor(model => model.CompanyId, htmlAttributes: new { #class = "control-label col-md-2" })
#*<div class="col-md-10">
#Html.EditorFor(model => model.CompanyId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CompanyId, "", new { #class = "text-danger" })
</div>*#
</div>
<!--DieShapeId-->
<div class="form-group">
#Html.LabelFor(model => model.DieShapeId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.DieShapeId, new SelectList(Model.DieShapes, "DieShapeId", "Name"))
#Html.ValidationMessageFor(model => model.DieShapeId, "", new {#class = "text-danger"})
</div>
</div>
<!--DieTypeId-->
<div class="form-group">
#Html.LabelFor(model => model.DieTypeId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.DieTypeId, new SelectList(Model.DieTypes, "DieTypeId", "Name"))
#Html.ValidationMessageFor(model => model.DieTypeId, "", new { #class = "text-danger" })
</div>
</div>
<!--Name-->
<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>
<!--Width-->
<div class="form-group">
#Html.LabelFor(model => model.Width, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Width, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Width, "", new { #class = "text-danger" })
</div>
</div>
<!--Height-->
<div class="form-group">
#Html.LabelFor(model => model.Height, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Height, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Height, "", new { #class = "text-danger" })
</div>
</div>
My controller:
DiesController.cs
using System.Net;
using System.Web.Mvc;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
using LabelArchive.Logic.Die;
using LabelArchive.Logic.DieShape;
using LabelArchive.Logic.DieType;
using LabelArchive.Models.Die;
namespace LabelArchive.Controllers
{
public class DiesController : Controller
{
// GET: Dies
public ActionResult Index()
{
return View();
}
// GET: Die_Read
public ActionResult Die_Read([DataSourceRequest] DataSourceRequest request)
{
var readRequest = Die.Get().ToDataSourceResult(request);
return Json(readRequest, JsonRequestBehavior.AllowGet);
}
// GET: Create
public ActionResult Create()
{
DieModel model = new DieModel();
model.DieShapes = DieShape.Get();
model.DieTypes = DieType.Get();
return View(model);
}
// POST: Create
[HttpPost]
public ActionResult Create(DieModel model)
{
if (ModelState.IsValid)
{
Die.Create(model);
return RedirectToAction("Index");
}
return View(model);
}
// GET: Edit
public ActionResult Edit(int id)
{
DieModel model = Die.Get(id);
return View(model);
}
// Post: Edit
[HttpPost]
public ActionResult Edit(DieModel model)
{
if (ModelState.IsValid)
{
Die.Update(model);
return RedirectToAction("Index");
}
return View(model);
}
// POST: Die_Destroy
[HttpPost]
public ActionResult Die_Destroy([DataSourceRequest] DataSourceRequest request, DieModel model)
{
if (model != null)
{
Die.Delete(model);
}
return Json(new[] { model }.ToDataSourceResult(request, ModelState));
}
}
}
My logic:
Dies.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using LabelArchive.Data;
using LabelArchive.Logic.AutomapperConfiguration;
using LabelArchive.Models.Die;
namespace LabelArchive.Logic.Die
{
public class Die
{
// IsModelValid
private static bool IsModelValid(DieModel model)
{
// If there is additional validation beyond data annotations, logic to process that additional validation goes here.
return true;
}
// Get
public static List<DieModel> Get(Expression<Func<Data.Die, bool>> predicate = null)
{
using (var db = new LabelArchiveEntities())
{
var mapper = DieMapper.Create();
List<DieModel> dies;
if (predicate == null)
{
dies = mapper.Map<List<DieModel>>(db.Dies.ToList());
}
else
{
dies = mapper.Map<List<DieModel>>(db.Dies.Where(predicate).ToList());
}
return dies;
}
}
// Get
public static DieModel Get(int id)
{
return Get(i => i.DieId == id).SingleOrDefault();
}
// Create
public static DieModel Create(DieModel model)
{
if (!IsModelValid(model))
{
throw new Exception("This model is invalid.");
}
var mapper = DieMapper.Create();
var die = mapper.Map<Data.Die>(model);
using (var db = new LabelArchiveEntities())
{
db.Dies.Add(die);
db.SaveChanges();
}
model.DieId = die.DieId;
return model;
}
// Update
public static DieModel Update(DieModel model)
{
if (!IsModelValid(model))
{
throw new Exception("This model is invalid.");
}
using (var db = new LabelArchiveEntities())
{
var mapper = DieMapper.Create();
var die = db.Dies.Find(model.DieId);
if (die != null)
{
mapper.Map(model, die);
db.SaveChanges();
}
}
return model;
}
// Delete
public static void Delete(DieModel model)
{
using (var db = new LabelArchiveEntities())
{
var die = db.Dies.Find(model.DieId);
if (die != null)
{
db.Dies.Remove(die);
db.SaveChanges();
}
}
}
}
}
My profile(mapping):
DieProfile.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using LabelArchive.Models.Die;
namespace LabelArchive.Logic.AutomapperConfiguration
{
public class DieProfile : Profile
{
protected override void Configure()
{
CreateMap<Data.Die, DieModel>()
.ForMember(d => d.DieShapeName, o => o.MapFrom(s => s.DieShape == null ? "" : s.DieShape.Name))
.ForMember(d => d.DieTypeName, o => o.MapFrom(s => s.DieType == null ? "": s.DieType.Name));
CreateMap<DieModel, Data.Die>();
}
}
public static class DieMapper
{
public static IMapper Create()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<DieProfile>();
});
return config.CreateMapper();
}
}
}
My Model:
DieModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LabelArchive.Models.DieShape;
using LabelArchive.Models.DieType;
namespace LabelArchive.Models.Die
{
public class DieModel
{
[Key]
public int DieId { get; set; }
public int CompanyId { get; set; }
public int DieShapeId { get; set; }
public int DieTypeId { get; set; }
public string DieShapeName { get; set; }
public string DieTypeName { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int Width { get; set; }
[Required]
public int Height { get; set; }
public IEnumerable<DieShapeModel> DieShapes { get; set; }
public IEnumerable<DieTypeModel> DieTypes { get; set; }
}
}

Drop down initiated when click on enter on validated text box

I've created a MVC5 App which was generated from my model by scaffold the view and controller,
In the model I have a drop down for dev and prod which is working fine, I have validation
for name for alpha-numeric and the problem is for e.g. user chooses prod (the second
option) and enters incorrect data in the name field and presses enter, the view is refreshed and
the drop down changes the selection from prod to dev. How can I avoid that?
How can I ask in the view if the type is different than dev, if so put the selected item?
Model:
public class Ad
{
public int ID { get; set; }
[RegularExpression(#"^[a-zA-Z0-9]*$", ErrorMessage = "Invalid Name")]
public string Name { get; set; }
public IEnumerable<SelectListItem> Type
{
get
{
return new[]
{
new SelectListItem {Value = "D", Text = "Dev"},
new SelectListItem {Value = "p", Text = "Prod"}
};
}
}
View:
<div class="form-group">
#Html.LabelFor(model => model.SystemType, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Type, Model.Type)
</div>
</div>
Edit the create operation
#model WebApplication3.Models.Ad
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
debugger;
$('select[name="Type"]').change(function () {
if ($(this).val() === 'p') {
$('input[name="User"]').prop("disabled", true);
$('input[name="Password"]').prop("disabled", true);
}
else {
$('input[name="User"]').prop("disabled", false);
$('input[name="Password"]').prop("disabled", false);
}
});
});
</script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Ad</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Type, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Type, Model.Type)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.User, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.User)
#Html.ValidationMessageFor(model => model.User)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</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>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
public class AdController : Controller
{
private AdDBContext db = new AdDBContext();
public ActionResult Index()
{
return View(db.Ad.ToList());
}
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Ad ad = db.Ad.Find(id);
if (ad == null)
{
return HttpNotFound();
}
return View(ad);
}
public ActionResult Create()
{
return View( new Ad());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="ID,Name,User,Password")] Ad ad)
{
if (ModelState.IsValid)
{
db.Ad.Add(ad);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(ad);
}
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Ad ad = db.Ad.Find(id);
if (ad == null)
{
return HttpNotFound();
}
return View(ad);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="ID,Name,User,Password")] Ad ad)
{
if (ModelState.IsValid)
{
db.Entry(ad).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(ad);
}
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Ad ad = db.Ad.Find(id);
if (ad == null)
{
return HttpNotFound();
}
return View(ad);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Ad ad = db.Ad.Find(id);
db.Ad.Remove(ad);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
On dropdown change event write the selected option value in a hidden field and when page refreshed get the value from hidden field and set the selected item from the action.
$('select#Type').change(function(){
$('#selectedOne').val($(this).val());
});
and in you action read from FormCollection and set selected item of the SelectList
Create Hidden Field in view:
<div class="form-group">
#Html.LabelFor(model => model.SystemType, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Type, Model.Type)
<input type="hidden" id="selectedOne" vlaue="" name="selectedOne" />
</div>
</div>
In your action:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="ID,Name,User,Password")] Ad ad,FormCollection form)
{
string selectedValue = form["selectedOne"].ToString();
if (ModelState.IsValid)
{
db.Ad.Add(ad);
db.SaveChanges();
return RedirectToAction("Index");
}
foreach(var item in ad.Type)
{
if(item.Value == selectedValue)
{
item.Selected = true;
}
}
return View(ad);
}
Solution 2:
Another simple solution is to use #Ajax.BeginForm Hepler instead of #Html.BeginForm, so that form posted via ajax, and your dropdown will not get reset.

Categories