locked
How to show saved value stored in database in Dropdownlist RRS feed

  • Question

  • User-826336654 posted

    Hi All,

    I think that it may be a simple thing but I couldn't figure in the last 3 days. I have a View in which there are 2 <g class="gr_ gr_19 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="19" data-gr-id="19">dropdownlists</g>, one for City and 2nd for County/District.

    I can load all Cities and Counties/Districts in the DropDownlist but once I save them in the database, How can I show the saved value again in the <g class="gr_ gr_20 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="20" data-gr-id="20">dropdownlist</g> for editing purpose? The code is below.

    Please Note that I am using DropDownList in Editor Templates.

    Model:

    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;
    
    namespace JIWebPictureDemo.Models
    {
        public class Student
        {
            public byte[] Photo { get; set; }
    
            [Display(Name = "Student Id:")]
            public int StudentId { get; set; }
    
            // Zero (0) for new and One (1) for update
            [HiddenInput(DisplayValue = false)]
            public int StudentType { get; set; }
    
            [Display(Name = "Full Name:")]
            [Required(ErrorMessage = "Full Name is required.")]
            public string FullName { get; set; }
    
            [Display(Name = "Email Address:")]
            [Required(ErrorMessage = "Email Address is required.")]
            public string Email { get; set; }
    
            [Display(Name = "Mobile:")]
            public string Mobile { get; set; }
    
            [Display(Name = "Telephone:")]
            public string Telephone { get; set; }
    
            [Display(Name = "Address 1:")]
            public string Address1 { get; set; }
    
            [Display(Name = "Address 2:")]
            public string Address2 { get; set; }
    
            [Display(Name = "City:")]
            [UIHint("CityComboBox")]
            public string City { get; set; }
    
            [Display(Name = "County:")]
            [UIHint("CountyComboBox")]
            public string County { get; set; }
    
            [Display(Name = "Post Code:")]
            public string PostCode { get; set; }
    
            [Display(Name = "Notes:")]
            [DataType(DataType.MultilineText)]
            public string Notes { get; set; }
        }
    }

    View:

    @model JIWebPictureDemo.Models.Student
    
    @{
        ViewBag.Title = "Index";
    }
    
    <script type="text/javascript">
        function OnBegin() {
            $('#progress').show();
        }
    
        function OnSuccess(response) {
            $('#progress').hide();
        }
    
        function OnFailure(response) {
            $('#progress').hide();
        }
    </script>
    
    @*@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))*@
    @using (Ajax.BeginForm("Index", "Home", FormMethod.Post, new AjaxOptions
    {
        OnSuccess = "OnSuccess",
        OnFailure = "OnFailure",
        OnBegin = "OnBegin",
        UpdateTargetId = "successmsg",
        LoadingElementId = "progress"
    }, new { enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()
        <div class="form">
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="row">
                <div class="col-md-2">
                    <div class="row">
                        <div class="col-md-12">
                            <br /> <br />
                            <a href="" onclick="ChangePicture(); return false">
                                <img id="image" src="~/Images/not-available.jpg" alt="" class="img-rounded img-border" width="160" height="160" />
                            </a>
                            <br />
                            <input accept="image/*" type="file" id="upload" name="file" onchange="ReadURL(this);" style="visibility: hidden;" />
                            @*<a href="" onclick="changePicture(); return false">Change Picture</a>*@
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <ul class="list-group">
                                <li class="list-group-item list-group-item-success">Result Info</li>
                                <li class="list-group-item list-group-item-success">Student Fees</li>
                                <li class="list-group-item list-group-item-success">Previous Qaulifications</li>
                            </ul>
                        </div>
                    </div>
                </div>
    
                <div class="col-md-10">
                    <div class="page-header">
                        <h3>Basic Information</h3>
                    </div>
    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                @Html.LabelFor(model => model.StudentId, htmlAttributes: new { @class = "control-label" })
                                @Html.EditorFor(model => model.StudentId, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly", @style = "max-width: 35%;" } })
                                @Html.ValidationMessageFor(model => model.StudentId, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                        <!-- hidden -->
                        <div class="col-md-6">
                            <div class="form-group">
                                @Html.EditorFor(model => model.StudentType, new { htmlAttributes = new { @class = "form-control" } })
                            </div>
                        </div>
                    </div>
    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                @Html.LabelFor(model => model.FullName, htmlAttributes: new { @class = "control-label" })
                                @Html.EditorFor(model => model.FullName, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter Full Name here" } })
                                @Html.ValidationMessageFor(model => model.FullName, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                        <div class="col-md-6">
                            <div class="form-group">
                                @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label" })
                                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter Email here" } })
                                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                        <div class="col-md-6">
                            <div class="form-group">
                                @Html.LabelFor(model => model.Mobile, htmlAttributes: new { @class = "control-label" })
                                @Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter Mobile Number here" } })
                                @Html.ValidationMessageFor(model => model.Mobile, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                        <div class="col-md-6">
                            <div class="form-group">
                                @Html.LabelFor(model => model.Telephone, htmlAttributes: new { @class = "control-label" })
                                @Html.EditorFor(model => model.Telephone, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter Telephone Number here" } })
                                @Html.ValidationMessageFor(model => model.Telephone, "", new { @class = "text-danger" })
                            </div>
                        </div>
                    </div>
    
                    <div class="page-header">
                        <h3>Address</h3>
                    </div>
    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                @Html.LabelFor(model => model.Address1, htmlAttributes: new { @class = "control-label" })
                                @Html.EditorFor(model => model.Address1, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter Street Address here" } })
                                @Html.ValidationMessageFor(model => model.Address1, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                        <div class="col-md-6">
                            <div class="form-group">
                                @Html.LabelFor(model => model.Address2, htmlAttributes: new { @class = "control-label" })
                                @Html.EditorFor(model => model.Address2, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter Local area name here" } })
                                @Html.ValidationMessageFor(model => model.Address2, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                        <div class="col-md-6">
                            <div class="form-group">
                                @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label" })
                                @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter City name here" } })
                                @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                        <div class="col-md-6">
                            <div class="form-group">
                                @Html.LabelFor(model => model.County, htmlAttributes: new { @class = "control-label" })
                                @Html.EditorFor(model => model.County, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter County name here" } })
                                @Html.ValidationMessageFor(model => model.County, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                        <div class="col-md-6">
                            <div class="form-group">
                                @Html.LabelFor(model => model.PostCode, htmlAttributes: new { @class = "control-label" })
                                @Html.EditorFor(model => model.PostCode, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter Post Code here" } })
                                @Html.ValidationMessageFor(model => model.PostCode, "", new { @class = "text-danger" })
                            </div>
                        </div>
                    </div>
    
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                @Html.LabelFor(model => model.Notes, htmlAttributes: new { @class = "control-label" })
                                @Html.EditorFor(model => model.Notes, new { htmlAttributes = new { @class = "form-control", @style = "max-width: 82%; height: 150px;" } })
                                @Html.ValidationMessageFor(model => model.Notes, "", new { @class = "text-danger" })
                            </div>
                        </div>
                    </div>
    
                    <div class="row">
                        <div class="form-group">
                            <div class="col-md-10">
                                <input type="submit" id="saverecord" data-target="#successErrorModel" value="Save Record" class="btn btn-primary" />
                                @Html.ActionLink("Back to List", "StudentList", "Home", null, new { @class = "btn btn-default" })
                            </div>
                        </div>
                    </div>
    
                </div>
            </div>
        </div>
    }
    
    <br />
    <div id="successmsg">
        @if (ViewBag.Message  != null)
        {
            <div class="alert alert-success alert-dismissable">
                @ViewBag.Message
                <a href="#" class="close" data-dismiss="alert">x</a>
            </div>
        }
    </div>
    
    <div id="progress" class="modal">
        <div class="center">
            <img src="~/Images/loader.gif" />
        </div>
    </div>

    Controller:

    using JIWebPictureDemo.Models;
    using JIWebPictureDemo.Models.General;
    using JIWebPictureDemo.ViewModels.Students;
    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.Mvc;
    
    namespace JIWebPictureDemo.Controllers
    {
        public class HomeController : Controller
        {
            // GET: Home
            public ActionResult Index()
            {
                StudentViewModel svm = new StudentViewModel();
                Student student = new Student
                {
                    StudentId = svm.GenerateStudentId()
                };
    
                return View(student);
            }
    
            [HttpPost, ValidateAntiForgeryToken]
            public ActionResult Index(Student student, HttpPostedFileBase file)
            {
                if (ModelState.IsValid)
                {
                    if (file != null && file.ContentLength > 0)
                    {
                        student.Photo = new byte[file.ContentLength];
                        file.InputStream.Read(student.Photo, 0, file.ContentLength);
                    }
    
                    if (student.StudentType == (int)StudentType.Insert)
                    {
                        StudentViewModel svm = new StudentViewModel();
                        svm.InsertStudentInfo(student);
    
                        ViewBag.Message = "Student Details are saved successfully.";
                    }
                    else
                    {
                        StudentViewModel svm = new StudentViewModel();
                        svm.UpdateStudentInfo(student);
    
                        ViewBag.Message = "Student Details is updated successfully.";
                    }
    
                    return JavaScript("window.location = '" + Url.Action("Edit", "Home", new { id = student.StudentId }) + "'");
                }
    
                return View(student);
            }
    
            [HttpGet]
            public ActionResult Edit(int id)
            {
                StudentViewModel svm = new StudentViewModel();
                Student student = svm.GetStudentDetailsByStudentId(id);
    
                // Initialise Student Type, in this case it is update so 1 or Update.
                student.StudentType = (int)StudentType.Update;
    
                return View("~/Views/Home/Index.cshtml", student);
            }
    
        }
    }

    Editor Template for City:

    @using JIWebPictureDemo.ViewModels.Students
    @using JIWebPictureDemo.Models.General
    
    @Html.DropDownList("", new SelectList(ComboBoxData.GetListData(ListType.City), "Value", "Text"), string.Empty, new { @class = "form-control" })
    

    Editor Template for County:

    @using JIWebPictureDemo.ViewModels.Students
    @using JIWebPictureDemo.Models.General
    
    @Html.DropDownList("", new SelectList(ComboBoxData.GetListData(ListType.County), "Value", "Text"), string.Empty, new { @class = "form-control" })
    

    Ado.Net code:

    using JIWebPictureDemo.Models.General;
    using System.Collections.Generic;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web.Mvc;
    
    namespace JIWebPictureDemo.ViewModels.Students
    {
        public class ComboBoxData
        {
            public static SelectList GetListData(ListType listType)
            {
                List<SelectListItem> list = new List<SelectListItem>();
    
                using (SqlConnection conn = new SqlConnection(AppSetting.ConnectionString()))
                {
                    using (SqlCommand cmd = new SqlCommand("usp_ListTypesDataGetDataByListType", conn))
                    {
                        cmd.CommandType = System.Data.CommandType.StoredProcedure;
    
                        conn.Open();
                        cmd.Parameters.AddWithValue("@ListTypeId", listType);
    
                        SqlDataReader reader = cmd.ExecuteReader();
    
                        while (reader.Read())
                        {
                            SelectListItem sli = new SelectListItem
                            {
                                Text = reader["Description"].ToString(),
                                Value = reader["Id"].ToString()
                            };
    
                            list.Add(sli);
                        }
                    }
                }
    
                SelectList selectList = new SelectList(list.AsEnumerable(), "Value", "Text");
    
                return selectList;
    
            }
        }
    }

    Thanks in advance

    Regards

    Thursday, January 3, 2019 5:25 PM

Answers

  • User-826336654 posted

    <g class="gr_ gr_15 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" id="15" data-gr-id="15">Thanks</g> everyone for the reply. But I have solved it myself. The problem was DropDownList was loaded after data was coming from <g class="gr_ gr_962 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep" id="962" data-gr-id="962">database</g> (it should suppose to be other way around), which makes <g class="gr_ gr_377 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="377" data-gr-id="377">dropdownlist</g> empty as nothing was selected. I have used ViewBag, which I wanted to avoid. The new code is below. The code highlighted with the yellow background is the new code.

    Controller:

    using JIWebPictureDemo.Models;
    using JIWebPictureDemo.Models.General;
    using JIWebPictureDemo.ViewModels.Students;
    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.Mvc;
    
    namespace JIWebPictureDemo.Controllers
    {
        public class HomeController : Controller
        {
            // GET: Home
            public ActionResult Index()
            {
                StudentViewModel svm = new StudentViewModel();
                Student student = new Student
                {
                    StudentId = svm.GenerateStudentId()
                };
    
                return View(student);
            }
    
            [HttpPost, ValidateAntiForgeryToken]
            public ActionResult Index(Student student, HttpPostedFileBase file)
            {
                if (ModelState.IsValid)
                {
                    if (file != null && file.ContentLength > 0)
                    {
                        student.Photo = new byte[file.ContentLength];
                        file.InputStream.Read(student.Photo, 0, file.ContentLength);
                    }
    
                    if (student.StudentType == (int)StudentType.Insert)
                    {
                        StudentViewModel svm = new StudentViewModel();
                        svm.InsertStudentInfo(student);
    
                        ViewBag.Message = "Student Details are saved successfully.";
                    }
                    else
                    {
                        StudentViewModel svm = new StudentViewModel();
                        svm.UpdateStudentInfo(student);
    
                        ViewBag.Message = "Student Details are updated successfully.";
                    }
    
                    //return PartialView("~/Views/Shared/PartialPages/SuccessDialogBox.cshtml");
                    return JavaScript("window.location = '" + Url.Action("Edit", "Home", new { id = student.StudentId }) + "'");
                }
    
                return View(student);
            }
    
            [HttpGet]
            public ActionResult Edit(int id)
            {
                StudentViewModel svm = new StudentViewModel();
                Student student = svm.GetStudentDetailsByStudentId(id);
    
                // Initialise Student Type, in this case it is update so 1 or Update.
                student.StudentType = (int)StudentType.Update;
                ViewBag.City = student.City;
                ViewBag.County = student.County;
    
                return View("~/Views/Home/Index.cshtml", student);
            }
        }
    }

    Editor Template for City:

    @using JIWebPictureDemo.ViewModels.Students
    @using JIWebPictureDemo.Models.General
    
    @Html.DropDownList("", new SelectList(ComboBoxData.GetListData(ListType.City), "Value", "Text", ViewBag.City), string.Empty, new { @class = "form-control" })
    

    Editor Template for County:

    @using JIWebPictureDemo.ViewModels.Students
    @using JIWebPictureDemo.Models.General
    
    @Html.DropDownList("", new SelectList(ComboBoxData.GetListData(ListType.County), "Value", "Text", ViewBag.County), string.Empty, new { @class = "form-control" })

    Regards

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 4, 2019 3:58 PM

All replies

  • User-474980206 posted

    because you are using @Html.DropdownList(), your code is responsible for setting the selected item in the list (.Selected = true) that matches the post back value. you could pass the current value to your ComboBoxData.GetListData() and it could set the selected item when building the list.

    Thursday, January 3, 2019 11:40 PM
  • User1724605321 posted

    Hi eaak79,

    You can pass the first parameter of dropdownlist which means that the selected value will bind to a model or ViewBag property :

    @Html.DropDownList("City", new SelectList(ComboBoxData.GetListData(ListType.City), "Value", "Text"), string.Empty, new { @class = "form-control" })

    Please refer to below document for more details about the control :

    http://www.tutorialsteacher.com/mvc/htmlhelper-dropdownlist-dropdownlistfor 

    Best Regards,

    Nan Yu

    Friday, January 4, 2019 9:26 AM
  • User-826336654 posted

    because you are using @Html.DropdownList(), your code is responsible for setting the selected item in the list (.Selected = true) that matches the <g class="gr_ gr_91 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del" id="91" data-gr-id="91">post back</g> value. you could pass the current value to your ComboBoxData.GetListData() and it could set the selected item when building the list.

    Can you please give me a simple example? thanks

    Friday, January 4, 2019 12:59 PM
  • User-826336654 posted

    Hi eaak79,

    You can pass the first parameter of dropdownlist which means that the selected value will bind to a model or ViewBag property :

    @Html.DropDownList("City", new SelectList(ComboBoxData.GetListData(ListType.City), "Value", "Text"), string.Empty, new { @class = "form-control" })

    <g class="gr_ gr_76 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" id="76" data-gr-id="76">Thanks</g> Nan Yu, Done it as per your reply but now it is giving me <g class="gr_ gr_4 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="4" data-gr-id="4">error</g> that the stored procedure expects @City and @County parameter as they are null but I have supplied the value. So don't know what to do next.

    Friday, January 4, 2019 1:39 PM
  • User-826336654 posted

    <g class="gr_ gr_15 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" id="15" data-gr-id="15">Thanks</g> everyone for the reply. But I have solved it myself. The problem was DropDownList was loaded after data was coming from <g class="gr_ gr_962 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep" id="962" data-gr-id="962">database</g> (it should suppose to be other way around), which makes <g class="gr_ gr_377 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="377" data-gr-id="377">dropdownlist</g> empty as nothing was selected. I have used ViewBag, which I wanted to avoid. The new code is below. The code highlighted with the yellow background is the new code.

    Controller:

    using JIWebPictureDemo.Models;
    using JIWebPictureDemo.Models.General;
    using JIWebPictureDemo.ViewModels.Students;
    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.Mvc;
    
    namespace JIWebPictureDemo.Controllers
    {
        public class HomeController : Controller
        {
            // GET: Home
            public ActionResult Index()
            {
                StudentViewModel svm = new StudentViewModel();
                Student student = new Student
                {
                    StudentId = svm.GenerateStudentId()
                };
    
                return View(student);
            }
    
            [HttpPost, ValidateAntiForgeryToken]
            public ActionResult Index(Student student, HttpPostedFileBase file)
            {
                if (ModelState.IsValid)
                {
                    if (file != null && file.ContentLength > 0)
                    {
                        student.Photo = new byte[file.ContentLength];
                        file.InputStream.Read(student.Photo, 0, file.ContentLength);
                    }
    
                    if (student.StudentType == (int)StudentType.Insert)
                    {
                        StudentViewModel svm = new StudentViewModel();
                        svm.InsertStudentInfo(student);
    
                        ViewBag.Message = "Student Details are saved successfully.";
                    }
                    else
                    {
                        StudentViewModel svm = new StudentViewModel();
                        svm.UpdateStudentInfo(student);
    
                        ViewBag.Message = "Student Details are updated successfully.";
                    }
    
                    //return PartialView("~/Views/Shared/PartialPages/SuccessDialogBox.cshtml");
                    return JavaScript("window.location = '" + Url.Action("Edit", "Home", new { id = student.StudentId }) + "'");
                }
    
                return View(student);
            }
    
            [HttpGet]
            public ActionResult Edit(int id)
            {
                StudentViewModel svm = new StudentViewModel();
                Student student = svm.GetStudentDetailsByStudentId(id);
    
                // Initialise Student Type, in this case it is update so 1 or Update.
                student.StudentType = (int)StudentType.Update;
                ViewBag.City = student.City;
                ViewBag.County = student.County;
    
                return View("~/Views/Home/Index.cshtml", student);
            }
        }
    }

    Editor Template for City:

    @using JIWebPictureDemo.ViewModels.Students
    @using JIWebPictureDemo.Models.General
    
    @Html.DropDownList("", new SelectList(ComboBoxData.GetListData(ListType.City), "Value", "Text", ViewBag.City), string.Empty, new { @class = "form-control" })
    

    Editor Template for County:

    @using JIWebPictureDemo.ViewModels.Students
    @using JIWebPictureDemo.Models.General
    
    @Html.DropDownList("", new SelectList(ComboBoxData.GetListData(ListType.County), "Value", "Text", ViewBag.County), string.Empty, new { @class = "form-control" })

    Regards

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 4, 2019 3:58 PM