0

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>

1 Answer 1

1
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();
Sign up to request clarification or add additional context in comments.

4 Comments

I was wanting to narrow down the records in the controller can I do a SQL action in the controller like that and if so can you show me where I would put it in my controller? Thanks for you help! Upvote for responding so quick!
Yes Version is a property of db.iamp_mapping do I want to put it in the first edit method or the post edit method because when I put the first edit method it threw an error "The entity or complex type 'NdeModel.iamp_mapping' cannot be constructed in a LINQ to Entities query. "
Not familiar enough with what you are doing to say, sorry.
How can I clarify my question for you? :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.