MVC3 razor Webgrid -retaining page after a delete - asp.net-mvc-3

On my MVC3 razor page, I am using a webgrid to show a list of approx 100 plus records.
I am setting a page size to 10 and paging and sorting is working fine. My only issue here is on my page I have a "delete" hyperlink on the webgrid. When I click "delete", it will delete the record and reload the page. But when reloading the page it goes back to the page1
For instance, if I am on page4 and I click "delete", it deletes that record and comes to the page1, but I want to remain in page4 itself. Any suggestions on how to achieve this.
public ViewResult Index(int? page, string sort)
{
var startPage = 0;
if (page.HasValue && page.Value > 0)
{
startPage = page.Value - 1;
}
vm.Employees = GetAllEmployeeData(startPage, vm.PageSize, sort);
vm.TotalRecords = context.TableEmployee.Count();
return View(vm);
}
public IEnumerable<Employees> GetAllEmployeeData(int page, int records, string sort)
{
IEnumerable<Employees> EmployeeData = null;
EmployeeData = context.TableEmployee.Where(e => e.IsActivated == true)
.Select(e => new Employees{ EmpID = e.EmpID, Name= e.Name, Joiningdate = e.Joiningdate , Department = e.DeptName}).AsEnumerable<Employees>();
switch (sort)
{
case "Department":
EmployeeData = EmployeeData .OrderBy(r => r.Department);
break;
case "JoiningDate":
EmployeeData = EmployeeData .OrderBy(r => r.JoiningDate);
break;
default:
EmployeeData = EmployeeData .OrderBy(r => r.Name);
break;
}
EmployeeData = EmployeeData .Skip(page * records).Take(records).ToList();
return EmployeeData ;
}
public ActionResult DeleteSelectedEmployee(int empId)
{
ContentsViewModel model = new ContentsViewModel();
int timelineItemId = 0;
EmployeeData E = context.TableEmployee.Find(empId);
context.TableEmployee.Remove(E);
context.SaveChanges();
return RedirectToAction("Index");
}
Here is my webgrid
#{var webgrid = new WebGrid(canPage: true, rowsPerPage: Model.PageSize, canSort: true, ajaxUpdateContainerId: "grid");
webgrid.Bind(Model.Employees, rowCount: Model.TotalRecords, autoSortAndPage: false);
webgrid.Pager(WebGridPagerModes.Numeric);
#webgrid.GetHtml(tableStyle: "webgridTable", htmlAttributes: new { id = "grid" },
columns: webgrid.Columns(
webgrid.Column("Name", "Name"),
webgrid.Column("Department", "Department"),
webgrid.Column("JoiningDate", "Join Date", format: #<text>#item.JoiningDate.ToString("dddd, MMMM d, yyyy")</text>),
webgrid.Column(header: "Action", format: (item) => Html.ActionLink("Edit", "Edit", new { empId = item.EmpID })),
webgrid.Column(format: (item) => Html.ActionLink("Delete", "Delete Record", new { empId = item.EmpID }))
));
}

Related

has error after add pagedList.Mvc package to my project

I wanted to add page number with a pagedList.MVC package into my razor view page so I added package and then it's my Controller:
public ViewResult Index(string sortOrder, string currentFilter, string searchPathId, int? page)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.IdPercorsoSortParm = String.IsNullOrEmpty(sortOrder) ? "IdPercorso_desc" : "";
if (searchPathId != null)
{
page = 1;
}
else
{
searchPathId = currentFilter;
}
ViewBag.CurrentFilter = searchPathId;
var listPercorsiModel = from listObj in _context.PercorsiModel
orderby listObj.IdPercorso
select listObj;
if (!String.IsNullOrEmpty(searchPathId))
{
//listPercorsiModel = listPercorsiModel.Where(s => s.IdPercorso == (System.Convert.ToInt32(searchPathId))).ToList();
}
switch (sortOrder)
{
case "IdPercorso_desc":
listPercorsiModel = listPercorsiModel.OrderByDescending(s => s.IdPercorso);
break;
//case "Date":
// students = students.OrderBy(s => s.EnrollmentDate);
// break;
//case "date_desc":
// students = students.OrderByDescending(s => s.EnrollmentDate);
// break;
}
int pageSize = 3;
int pageNumber = (page ?? 1);
//return View(students.ToPagedList(pageNumber, pageSize));
return View(listPercorsiModel.ToPagedList(pageNumber, pageSize));
}
and then in my view after add this code i had error:
#Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
my error:
ok, want to inform that because I used .net core application had a problem and I found another package for paging number and its working perfect:
x.pagedlist.mvc.core

Using Devexpress MVC TreeList to list order totals by client

I'm trying to implement a DevExpress MVC TreeList that shows a list of clients as the first level of the hierarchy. But when you open one client, the second level must show a list of related orders with their OrderTotal for each order.
I'm trying to base myself on the demo at http://demos.devexpress.com/MVCxTreeListDemos/DataBinding/DataBinding which is similar to what I'm looking for. I'm using the Northwind database as an example.
The model that the TreeList must be based on has to be specific in that it has to have the following structure (maybe I'm wrong on this):
CustomerId,
Order.CustomerId,
CustomerName,
OrderTotal,
OrderDate,
ShipCity
The second one has to be the "ParentId" in order to satisfy the hierarchy structure.
Here is what I have in my controller:
[ValidateInput(false)]
public ActionResult OrderTreeListPartial()
{
var model = db.Orders.GroupBy(o => o.Customer)
.Select(group => new
{
CustomerId = group.Key.CustomerID,
ParentId = group.Select(g=>g.CustomerID),
CustomerName = group.Key.CompanyName,
OrderTotal = group.Sum(g => g.OrderTotal),
OrderDate = group.Select(g => g.OrderDate),
City = group.Select(g => g.ShipCity)
});
return PartialView("_OrderTreeListPartial", model);
}
And I have the following in my _OrderTreeListPartial:
#{
var treeList = Html.DevExpress().TreeList(settings =>
{
settings.Name = "OrderTreeList";
settings.CallbackRouteValues = new { Controller = "TreeList", Action = "OrderTreeListPartial" };
settings.SettingsEditing.AddNewNodeRouteValues = new { Controller = "TreeList", Action = "OrderTreeListPartialAddNew" };
settings.SettingsEditing.UpdateNodeRouteValues = new { Controller = "TreeList", Action = "OrderTreeListPartialUpdate" };
settings.SettingsEditing.DeleteNodeRouteValues = new { Controller = "TreeList", Action = "OrderTreeListPartialDelete" };
settings.SettingsEditing.NodeDragDropRouteValues = new { Controller = "TreeList", Action = "OrderTreeListPartialMove" };
settings.CommandColumn.Visible = true;
settings.CommandColumn.NewButton.Visible = true;
settings.CommandColumn.DeleteButton.Visible = true;
settings.CommandColumn.EditButton.Visible = true;
settings.AutoGenerateColumns = false;
settings.KeyFieldName = "CustomerId";
settings.ParentFieldName = "ParentId";
settings.RootValue = 0;
settings.Columns.Add(
column =>
{
column.FieldName = "CustomerName";
}
);
settings.Columns.Add(
column =>
{
column.FieldName = "OrderDate";
}
);
settings.Columns.Add(
column =>
{
column.FieldName = "OrderTotal";
column.PropertiesEdit.DisplayFormatString = "{0:C}";
}
);
settings.Columns.Add(
column =>
{
column.FieldName = "City";
}
);
settings.SettingsPager.Visible = true;
settings.SettingsSelection.Enabled = true;
});
if (ViewData["EditError"] != null)
{
treeList.SetEditErrorText((string)ViewData["EditError"]);
}
}
#treeList.Bind(Model).GetHtml()
I think the problem is in my LINQ expression in my controller. The truth is I'm not an expert in LINQ and I'm evaluating the DevExpress extensions for a future project. Any help would be appreciated, wether in my LINQ or in how I prepared the TreeList.
You didn't really specify your problem but I think you shouldn't do the grouping in advance as this results in list of groups.
Just create a DataTable with the columns "CustomerId" and "ParentId".
The TreeList will then do the grouping

MVC ListBox Selected Values

New to MVC and Stackoverflow so sorry for not having enough reputation to post images...
Trying to render a ListBox with pre selected values
My SQL Database:
http://i.imgur.com/bcdXyqE.png
My Entity Framework
http://i.imgur.com/wYWXuAq.png
My Controller
public ActionResult AccessRights(int id)
{
var user = db.User.Find(id);
var roles = db.Role;
var newList = new List<SelectListItem>();
foreach (var role in roles)
{
newList.Add(
new SelectListItem()
{
Value = role.Id.ToString(),
Text = role.RoleName,
Selected = user.Role.Contains(role)
}
);
}
ViewBag.x = new SelectList(newList, "Value", "Text");
ViewBag.Roles = new SelectList(db.Role, "Id", "RoleName", user.Role);
return View(user);
}
My View
<p>try1:</p>
#Html.ListBox("Roles", null, new { #class = "form-control", #size = 6, #style = "height: initial" })
<p>try2:</p>
#Html.ListBox("x", null, new { #size = 6, #style = "height: initial" })
Non of the 2 tries renders with pre selected values?
got it working.
public ActionResult AccessRights(int id)
{
var user = db.User.Find(id);
IEnumerable<SelectListItem> roles = db.Role.Select(c => new SelectListItem{ Value = c.Id.ToString(), Text = c.RoleName, Selected = true});
var rolesSelected = new int[user.Role.Count];
var i = 0;
foreach (var role in user.Role)
{
rolesSelected[i] = role.Id;
i++;
}
ViewBag.Roles = roles.ToList();
ViewBag.RolesSelected = rolesSelected;
return View(user);
}
#Html.ListBox("RolesSelect", new MultiSelectList(ViewBag.Roles, "Value", "Text", ViewBag.RolesSelected), new { #class = "form-control", #size = 6, #style = "height: initial" })

the paging of Grid.MVC not work

Im using Grid.MVC in my MVC web application
When test it in a blank page with index controller it works successfully with pagination and filtration.
The Problem accrue when i put it in my project
the steps that i do that i make ajax request (because i don't need to reload the page) to method and return a partial view that contains the result of the search by the Grid.Mvc the result and number of pages return successfully but when i press to next page or filter it doesn't work.
Code:
View:
#using (Ajax.BeginForm("Search", "Home",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "SearchResult"
})){
#Html.DropDownList("Province", "Province")
#Html.DropDownList("Cities", "Cities")
<span>price from :</span> <input type="text" name="Pricefrom" />
<span>to :</span> <input type="text" name="Priceto" />
<input type="submit" value="Search" /> }
Search Controller :
[HttpPost]
public ActionResult Search(int? page , int Province = 0, int Cities = 0, int Pricefrom = 0, int Priceto = 0)
{
var ads = db.Ad.Where(a => (Cities == 0 || a.CityId == Cities) &&
(Province == 0 || a.Cities.ProvinceId == Province)&&
(Pricefrom == 0 || a.Price >= Pricefrom)&&
(Priceto == 0 || a.Price <= Priceto)).OrderBy(a => a.AdDate).ToList();
return PartialView("_Search", ads);
}
PartialView:
#using GridMvc.Html
#model IEnumerable<Semsark.Areas.Backend.Models.Ad>
<div>
#Html.Grid(Model).Columns(columns =>
{
columns.Add(c => c.Id).Titled("ID");
columns.Add(c => c.AdTitle).Titled("title");
columns.Add(c => c.AdBody).Titled("body");
}).WithPaging(2).Sortable(true)
</div>
scripts and styles in the View index.cshtml :
<head>
<meta name="viewport" content="width=device-width" />
<link href="#Url.Content("~/Content/Gridmvc.css")" rel="stylesheet" />
<script src="#Url.Content("~/Scripts/gridmvc.min.js")"></script>
<script src="~/Scripts/gridmvc.lang.ru.js"></script>
<title>Index</title>
Thanks in advance for any help,
#*Webgrid using Paging in mvc 4.
View Page **.cshtml** *#
#model MvcPopup.Models.PagedEmployeeModel
#{
//ViewBag.Title = "SearchEmployee";
Layout = null;
}
#{
WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize);
grid.Bind(Model.Employee,
autoSortAndPage: false,
rowCount: Model.TotalRows
);
}
#grid.GetHtml(
fillEmptyRows: false,
alternatingRowStyle: "alternate-row",
headerStyle: "grid-header",
footerStyle: "grid-footer",
mode: WebGridPagerModes.All,
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
columns: new[] {
grid.Column("Name",
header: "Name",
format: #<text>
#Html.ActionLink((string)item.Name, "ViewEmployeeDetail", new { id = item.id }, new { #class = "viewDialog" })</text>
),
grid.Column("Department"),
grid.Column("City"),
grid.Column("State"),
grid.Column("Country",
header: "Country"
),
grid.Column("Mobile"),
grid.Column("",
header: "Actions",
format: #<text>
#Html.ActionLink("Edit", "EditEmployee", new { id = item.id }, new { #class = "editDialog" })
|
#Html.ActionLink("Delete", "Delete", new { id = item.id }, new { #class = "confirmDialog"})
</text>
)
})
#*-----------------------------------
Model folder under modelservices.cs file
=================================*#
public IEnumerable<Employee> GetEmployeePage(int pageNumber, int pageSize, string searchCriteria)
{
if (pageNumber < 1)
pageNumber = 1;
return db.Employees
.OrderBy(m =>m.Name)
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize)
.ToList();
}
public int CountAllEmployee()
{
return db.Employees.Count();
}
public class PagedEmployeeModel
{
public int TotalRows { get; set; }
public IEnumerable<Employee> Employee { get; set; }
public int PageSize { get; set; }
}
#*Controller folder under create file like employeecontroller.cs *#
using MvcPopup.Models;
using System.Globalization;
using System.Text;
namespace MvcPopup.Controllers
{
public class EmployeeController : Controller
{
//
// GET: /Employee/
ModelServices mobjModel = new ModelServices();
public ActionResult Index()
{
return View();
}
public ActionResult SearchEmployee(int page = 1, string sort = "name", string sortDir = "ASC")
{
const int pageSize = 5;
var totalRows = mobjModel.CountAllEmployee();
sortDir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? sortDir : "asc";
var validColumns = new[] { "id", "name", "department", "country" };
if (!validColumns.Any(c => c.Equals(sort, StringComparison.CurrentCultureIgnoreCase)))
sort = "id";
var employee = mobjModel.GetEmployeePage(page, pageSize, "it." + sort + " " + sortDir);
var data = new PagedEmployeeModel()
{
TotalRows = totalRows,
PageSize = pageSize,
Employee = employee
};
return View(data);
}
------------------------
Have you tried to pass through an IQueryable list instead of an IEnumerable? According to the documentation, Gridmvc.Html requires an IQueryable for paging. There are some subtle differences between IQueryable and IEnumerable that might make a difference here.
These scripts are needed for paging:
"~/Scripts/GridMvc/URI.js"
"~/Scripts/GridMvc/gridmvc.min.js"
"~/Scripts/GridMvc/gridmvc-ext.js"

Using MultiSelect List in MVC 3

Right now I am working on a multiselect list in MVC 3. I was able to get over a big hurdle earlier today which was populating the dropdown list with version data from the database. The problem is that it is showing every item that is in the table column VERSION. I know that this is a simple fix but I can't seem to figure it out.... I was thinking that all I have to do is add an if statement with an enumerator that says something like the following psudocode.
while VERSION <> null
if version = version
then don't display version
end while
At the moment it is displaying all 387 rows of VERSION and all I need it to display is the first instance of a version so if the version was 1.5 it only displays the first one so I can grab it for another record, I hope this makes sense. I have included my controller class and my edit class below. Please let me know if you need any of my other classes for diagnosis. Thanks for your HELP!
EDIT 04/11/12
It seems that I need to clarify my request some so here is my attempt at that for you guys.
What I need help with is fixing the selectList code so it only returns the first instance of a VERSION. At the moment when I click on the drop down it is filled with every row from the column VERSION which means that I have 385 instances in the drop down saying version 1.2 and two instances of 1.3. What I would like it to do is to fill the drop down with just two instances of the version 1.2 and 1.3. PLEASE HELP I would offer a bounty if I had more points but I am new so all I can say is if you help at all I promise to upvote! Thanks for your help!
PACONTROLLER.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Web.UI.WebControls;
using System.Web;
using System.Web.Mvc;
using DBFirstMVC.Models;
using System.Data;
using PagedList;
using PagedList.Mvc;
using DBFirstMVC.Controllers;
using System.IO;
using DBFirstMVC;
using System.Web.UI;
namespace DBFirstMVC.Controllers
{
public class PaController : Controller
{
PaEntities db = new PaEntities();
// Index Method
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewBag.CurrentSort = sortOrder; //ViewBag property provides the view with the current sort order
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "PA desc" : ""; // Calls the sortOrder switch/case PA desc or default
ViewBag.MPSortParm = sortOrder == "MP" ? "MP desc" : "MP asc"; // Calls the sortOrder switch/case MP desc or MP asc
ViewBag.IASortParm = sortOrder == "IA" ? "IA desc" : "IA asc"; // Calls the sortOrder switch/case IA desc or IA asc
ViewBag.VersionSortParm = sortOrder == "VERSION" ? "Version desc" : "Version asc"; // Calls the sortOrder switch/case Version desc or Version asc
ViewBag.IAMP_PKSortParm = sortOrder == "IAMP_PK" ? "IAMP_PK desc" : "IAMP_PK asc"; // Calls the sortOrder switch/case IAMP_PK desc or IAMP_PK asc
if (Request.HttpMethod == "GET")
{
searchString = currentFilter; //sets the currentFilter equal to Searchstring
}
else
{
page = 1; // defaults to page 1
}
ViewBag.CurrentFilter = searchString; // Provides the view with the current filter string
var IAMP = from p in db.iamp_mapping select p;
if (!String.IsNullOrEmpty(searchString))
{
IAMP = IAMP.Where(p => p.PA.ToUpper().Contains(searchString.ToUpper())); //selects only records that contains the search string
}
switch (sortOrder) // switch case changes based on desired sort
{
case "Pa desc":
IAMP = IAMP.OrderByDescending(p => p.PA);
break;
case "MP desc":
IAMP = IAMP.OrderByDescending(p =>p.MAJOR_PROGRAM);
break;
case "MP asc":
IAMP = IAMP.OrderBy(p =>p.MAJOR_PROGRAM);
break;
case "IA desc":
IAMP = IAMP.OrderByDescending(p => p.INVESTMENT_AREA);
break;
case "IA asc":
IAMP = IAMP.OrderBy(p => p.INVESTMENT_AREA);
break;
case "Version asc":
IAMP = IAMP.OrderBy(p => p.VERSION);
break;
case "Version desc":
IAMP = IAMP.OrderByDescending(p => p.VERSION);
break;
case "IAMP_PK asc":
IAMP = IAMP.OrderBy(p => p.IAMP_PK);
break;
case "IAMP_PK desc":
IAMP = IAMP.OrderByDescending(p => p.IAMP_PK);
break;
default:
IAMP = IAMP.OrderBy(p => p.PA);
break;
}
int pageSize = 15; // number of records shown
int pageNumber = (page ?? 1); // start page number
return View(IAMP.ToPagedList(pageNumber, pageSize)); // uses pagedList method to return correct page values
}
// Instantiates create method
// GET: /Pa/Create
public ActionResult Create()
{
SetVersionViewBag();
return View();
}
// Create method adds records to Database and saves changes
// POST: /Pa/Create
[HttpPost]
public ActionResult Create(iamp_mapping IAMP)
{
try
{
using (var db = new PaEntities())
{
db.iamp_mapping.Add(IAMP);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
ViewBag.VERSION = new MultiSelectList(db.iamp_mapping, "VERSION", "VERSION", IAMP.VERSION);
return View(IAMP);
}
}
// Instantiates Edit Method
// GET: /Pa/Edit/5
public ActionResult Edit(string id)
{
using (var db = new PaEntities())
{
iamp_mapping IAMP = db.iamp_mapping.Find(id);
SetVersionViewBag(IAMP.VERSION);
return View(IAMP);
}
}
// Edit method modifies existing records and saves changes
// POST: /Pa/Edit/5
[HttpPost]
public ActionResult Edit(string id, iamp_mapping IAMP)
{
try
{
using (var db = new PaEntities())
{
db.Entry(IAMP).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("");
}
}
catch
{
SetVersionViewBag(IAMP.VERSION);
return View(IAMP);
}
}
// Instantiates delete method
// GET: /Pa/Delete/5
public ActionResult Delete(string id)
{
using (var db = new PaEntities())
{
return View(db.iamp_mapping.Find(id));
}
}
// Delete method renames primary key and then removes record from database
// POST: /Pa/Delete/5
[HttpPost]
public ActionResult Delete(string id, iamp_mapping IAMP)
{
try
{
using (var db = new PaEntities())
{
var vIAMP = db.iamp_mapping.Find(id);
db.Entry(vIAMP).State = EntityState.Deleted;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (Exception e)
{
throw (e);
//return View();
}
}
public ActionResult IAMP_Mapping(iamp_mapping IAMP)
{
var iamp_mapping = db.iamp_mapping as IEnumerable<iamp_mapping>;
var grid = new GridView
{
DataSource = from p in iamp_mapping
select new
{
PA = p.PA,
MP = p.MAJOR_PROGRAM,
IA = p.INVESTMENT_AREA,
VERSION = p.VERSION,
IAMP_PK = p.IAMP_PK
}
};
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-dispostion", "inline; filename= Excel.xls");
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
return View("Index");
}
public ActionResult SelectVersion() {
List<SelectListItem> versions = new List<SelectListItem>();
versions.Add(new SelectListItem { Text = "Action", Value = "0" });
versions.Add(new SelectListItem { Text = "Drama", Value = "1" });
versions.Add(new SelectListItem { Text = "Comedy", Value = "2", Selected = true });
versions.Add(new SelectListItem { Text = "Science Fiction", Value = "3" });
ViewBag.VersionType = versions;
return View();
}
public ViewResult VersionChosen(string VersionType)
{
ViewBag.messageString = VersionType;
return View("Information");
}
public enum eVersionCategories { Action, Drama, Comedy, Science_Fiction };
private void SetViewBagVersionType(eVersionCategories selectedVersion)
{
IEnumerable<eVersionCategories> values =
Enum.GetValues(typeof(eVersionCategories))
.Cast<eVersionCategories>();
IEnumerable<SelectListItem> versions =
from value in values
select new SelectListItem
{
Text = value.ToString(),
Value = value.ToString(),
Selected = value == selectedVersion,
};
ViewBag.VersionType = versions;
}
public ActionResult SelectVersionEnum()
{
SetViewBagVersionType(eVersionCategories.Drama);
return View("SelectVersion");
}
public ActionResult SelectVersionEnumPost()
{
SetViewBagVersionType(eVersionCategories.Comedy);
return View();
}
[HttpPost]
public ActionResult SelectVersionEnumPost(eVersionCategories VersionType)
{
ViewBag.messageString = VersionType.ToString() + " val = " + (int)VersionType;
return View("Information");
}
private void SetVersionViewBag(string VERSION = null)
{
if (VERSION == null)
ViewBag.VERSION = new MultiSelectList(db.iamp_mapping, "VERSION", "VERSION");
else
ViewBag.VERSION = new MultiSelectList(db.iamp_mapping.ToArray(), "VERSION", "VERSION", VERSION);
}
}
}
EDIT.CSHTML
#model DBFirstMVC.Models.iamp_mapping
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>iamp_mapping</legend>
<div class="editor-label">
#Html.LabelFor(model => model.PA)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PA)
#Html.ValidationMessageFor(model => model.PA)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.MAJOR_PROGRAM)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MAJOR_PROGRAM)
#Html.ValidationMessageFor(model => model.MAJOR_PROGRAM)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.INVESTMENT_AREA)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.INVESTMENT_AREA)
#Html.ValidationMessageFor(model => model.INVESTMENT_AREA)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.VERSION)
</div>
<div class="editor-field">
#Html.DropDownList("Version", ViewBag.Version as MultiSelectList)
#Html.ValidationMessageFor(model => model.VERSION)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.IAMP_PK)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.IAMP_PK)
#Html.ValidationMessageFor(model => model.IAMP_PK)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "")
</div>
SELECT DISTINCT
Version
FROM YourTable
This will give you a distinct list of versions. It's not clear what help you want with your controller and views.
Edit:
Or if you want to use linq in your controller (assuming that Version is a property of db.iamp_mapping)
db.iamp_mapping.Select(x => new iamp_mapping{Version = x.Version}).Distinct().ToList();

Resources