2

I created MVC project and use EF to get data,

Here is the table stucture for tblRecStatus

RecStatusId     int
RecStatusName   nvarchar(20)
RecStatusDecr   nvarchar(100)
CreateOn        datetime
CreateBy        int
ModifyOn        datetime
ModifyBy        int

And here is the table stucture for tblLogType

LogTypeId       int
LogTypeCode     nvarchar(2)
LogTypeName     nvarchar(20)
LogTypeDecr     nvarchar(100)
RecStatusId     int
CreateOn        datetime
CreateBy        int
ModifyOn        datetime
ModifyBy        int

tblLogType.RecStatusId have foreign key to tblRecStatus.RecStatusId

The DataAccess for LogTypeDA :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace i_insurance.DataAccess
{
    public class LogTypeDA : BaseDA
    {
        public List<tblLogType> GetAll()
        {
            return (from tblLogType o in this.DataContext.tblLogTypes
                    select o).ToList();
        }

        public tblLogType GetById(int Id)
        {
            return (from tblLogType o in this.DataContext.tblLogTypes
                    where o.LogTypeId == Id
                    select o).SingleOrDefault();
        }


        public void Insert(tblLogType tblLogType)
        {
            try
            {
                this.DataContext.tblLogTypes.Add(tblLogType);
                this.DataContext.SaveChanges();
            }
            catch (Exception)
            {

                throw;
            }

        }

        public void Delete(int Id)
        {
            try
            {
                tblLogType tblLogTypeOnDb = (from tblLogType o in this.DataContext.tblLogTypes
                                     where o.LogTypeId == Id
                                     select o).SingleOrDefault();

                this.DataContext.tblLogTypes.Remove(tblLogTypeOnDb);
                this.DataContext.SaveChanges();
            }
            catch (Exception)
            {

                throw;
            }

        }


        public void Update(tblLogType tblLogType)
        {
            try
            {
                tblLogType tblLogTypeOnDb = (from tblLogType o in this.DataContext.tblLogTypes
                                             where o.LogTypeId == tblLogType.LogTypeId
                                     select o).SingleOrDefault();

                tblLogTypeOnDb.LogTypeCode = tblLogType.LogTypeCode;
                tblLogTypeOnDb.LogTypeName = tblLogType.LogTypeName;
                tblLogTypeOnDb.LogTypeDecr = tblLogType.LogTypeDecr;
                tblLogTypeOnDb.RecStatusId = tblLogType.RecStatusId;
                tblLogTypeOnDb.ModifyOn = tblLogType.ModifyOn;
                tblLogTypeOnDb.ModifyBy = tblLogType.ModifyBy;

                this.DataContext.SaveChanges();
            }
            catch (Exception)
            {

                throw;
            }

        }

    }
}

The Model for this LogTypeModel :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.ComponentModel.DataAnnotations;
using System.Text;
using i_insurance.DataAccess;
using System.Web.Mvc;

namespace i_insurance.Models
{
    public class LogTypeModel
    {

        public class LogType
        {
            [Key]
            public int LogTypeId { get; set; }

            [Required(ErrorMessage = "Log Type Code is required.")]
            [Display(Name = "Log Type Code")]
            [MaxLength(2)]
            public string LogTypeCode { get; set; }

            [Required(ErrorMessage = "Log Type Name is required.")]
            [Display(Name = "Log Type Name")]
            [MaxLength(20)]
            public string LogTypeName { get; set; }

            [Display(Name = "Log Type Description")]
            [MaxLength(100)]
            public string LogTypeDecr { get; set; }

            [Display(Name = "Record Status")]
            public int? RecStatusId { get; set; }

            [DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy hh:mm:ss}", ApplyFormatInEditMode = true)]
            public DateTime? CreateOn { get; set; }

            public int? CreateBy { get; set; }

            [DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy hh:mm:ss}", ApplyFormatInEditMode = true)]
            public DateTime? ModifyOn { get; set; }

            public int? ModifyBy { get; set; }

            // additional column, example column from other table
            public string RecStatusName { get; set; }
            public string CreateByUserName { get; set; }
            public string ModifyByUserName { get; set; }

            public IEnumerable<SelectListItem> RecordStatusList { get; set; }

        }

        public LogTypeModel()
        {
            this.LogTypeList = new List<LogType>();
        }

        public List<LogType> LogTypeList { get; set; }




    }


}

Here is the Controller LogTypeController :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using i_insurance.Models;
using i_insurance.DataAccess;
using System.Data;
using System.Web.Security;
using i_insurance.Filters;
using i_insurance;



namespace i_insurance.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class LogTypeController : Controller
    {
        //
        // GET: /Log/




        public ActionResult Index()
        {
            return View();
        }


        public ActionResult LogTypeIndex()
        {
            LogTypeDA LogTypeDA = new LogTypeDA();
            List<tblLogType> lsTblLogType;

            lsTblLogType = LogTypeDA.GetAll();
            LogTypeModel model = new LogTypeModel();

            RecStatusDA RecStatusDA = new RecStatusDA();

            foreach (tblLogType o in lsTblLogType)
            {
                LogTypeModel.LogType LogType = new LogTypeModel.LogType();

                LogType.LogTypeId = o.LogTypeId;
                LogType.LogTypeCode = o.LogTypeCode;
                LogType.LogTypeName = o.LogTypeName;
                LogType.LogTypeDecr = o.LogTypeDecr;
                LogType.RecStatusId = o.RecStatusId;
                LogType.CreateOn = o.CreateOn;
                LogType.CreateBy = o.CreateBy;
                LogType.ModifyOn = o.ModifyOn;
                LogType.ModifyBy = o.ModifyBy;

                //additional column
                LogType.RecStatusName = o.tblRecStatu.RecStatusName;
                LogType.CreateByUserName = o.UserProfile.UserName;
                LogType.ModifyByUserName = o.UserProfile1.UserName;

                model.LogTypeList.Add(LogType);
            }

            return View(model);
        }




        //[HttpGet]
        public ActionResult LogTypeCreate()
        {
            //ViewBag.RecStatusList = new RecStatusDA().GetAll();
            //return View();
            var model = new LogTypeModel.LogType { RecordStatusList = HelperController.GetAllRecStatus() };
            return View(model);

        }

        [HttpPost]
        public ActionResult LogTypeCreate(LogTypeModel.LogType LogType)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    DateTime CurrentTime = new DateTime();
                    CurrentTime = DateTime.Now;

                    LogTypeDA LogTypeDA = new LogTypeDA();
                    tblLogType tblLogType = new tblLogType();

                    tblLogType.LogTypeCode = LogType.LogTypeCode;
                    tblLogType.LogTypeName = LogType.LogTypeName;
                    tblLogType.LogTypeDecr = LogType.LogTypeDecr;
                    tblLogType.RecStatusId = LogType.RecStatusId;
                    tblLogType.CreateOn = CurrentTime;
                    tblLogType.CreateBy = WebMatrix.WebData.WebSecurity.CurrentUserId;
                    tblLogType.ModifyOn = CurrentTime;
                    tblLogType.ModifyBy = WebMatrix.WebData.WebSecurity.CurrentUserId;

                    LogTypeDA.Insert(tblLogType);
                    return RedirectToAction("LogTypeIndex");
                }

            }
            catch (Exception)
            {

                throw;
            }
            return View(LogType);
        }


        // GET: /Log/LogTypeDelete/5
        public ActionResult LogTypeDelete(int Id, bool? saveChangesError)
        {
            if (saveChangesError.GetValueOrDefault())
            {
                ViewBag.ErrorMessage = "Unable to save changes. Try again, and if the problem persists see your system administrator.";
            }

            LogTypeDA LogTypeDA = new LogTypeDA();
            tblLogType tblLogType = new tblLogType();
            tblLogType = LogTypeDA.GetById(Id);

            LogTypeModel.LogType model = new LogTypeModel.LogType();
            model.LogTypeCode = tblLogType.LogTypeCode;
            model.LogTypeName = tblLogType.LogTypeName;
            model.LogTypeDecr = tblLogType.LogTypeDecr;


            return View(model);
        }


        // POST: /Log/LogTypeDelete/5
        [HttpPost, ActionName("LogTypeDelete")]
        public ActionResult LogTypeDelete(int Id)
        {
            LogTypeDA LogTypeDA = new LogTypeDA();
            LogTypeDA.Delete(Id);

            return RedirectToAction("LogTypeIndex");
        }


        public ActionResult LogTypeRead(int Id)
        {
            LogTypeDA LogTypeDA = new LogTypeDA();
            tblLogType tblLogType = LogTypeDA.GetById(Id);

            LogTypeModel.LogType model = new LogTypeModel.LogType();

            model.LogTypeId = tblLogType.LogTypeId;
            model.LogTypeCode = tblLogType.LogTypeCode;
            model.LogTypeName = tblLogType.LogTypeName;
            model.LogTypeDecr = tblLogType.LogTypeDecr;
            model.RecStatusId = tblLogType.RecStatusId;
            model.CreateOn = tblLogType.CreateOn;
            model.CreateBy = tblLogType.CreateBy;
            model.ModifyOn = tblLogType.ModifyOn;
            model.ModifyBy = tblLogType.ModifyBy;

            //for additional column
            model.RecStatusName = tblLogType.tblRecStatu.RecStatusName;
            model.CreateByUserName = tblLogType.UserProfile.UserName;
            model.ModifyByUserName = tblLogType.UserProfile1.UserName;


            return View(model);

        }

        // GET: /Log/LogTypeUpdate/5
        public ActionResult LogTypeUpdate(int Id)
        {
            LogTypeDA LogTypeDA = new LogTypeDA();
            tblLogType tblLogType = new tblLogType();
            tblLogType = LogTypeDA.GetById(Id);

            LogTypeModel.LogType model = new LogTypeModel.LogType();

            model.LogTypeId = Id;
            model.LogTypeCode = tblLogType.LogTypeCode;
            model.LogTypeName = tblLogType.LogTypeName;
            model.LogTypeDecr = tblLogType.LogTypeDecr;
            model.RecStatusId = tblLogType.RecStatusId;

            // for dropdownlist value
            //ViewBag.RecStatusList = new RecStatusDA().GetAll();
            model.RecordStatusList = HelperController.GetAllRecStatus();

            return View(model);

        }


        // POST: /Log/LogType/Edit/5
        [HttpPost]
        public ActionResult LogTypeUpdate(LogTypeModel.LogType LogType)
        {

            try
            {
                if (ModelState.IsValid)
                {
                    LogTypeDA LogTypeDA = new LogTypeDA();
                    tblLogType tblLogType = new tblLogType();

                    DateTime CurrentDateTime = new DateTime();
                    CurrentDateTime = DateTime.Now;


                    tblLogType.LogTypeId = LogType.LogTypeId;
                    tblLogType.LogTypeCode = LogType.LogTypeCode;
                    tblLogType.LogTypeName = LogType.LogTypeName;
                    tblLogType.LogTypeDecr = LogType.LogTypeDecr;
                    tblLogType.RecStatusId = LogType.RecStatusId;
                    tblLogType.ModifyOn = CurrentDateTime;
                    tblLogType.ModifyBy = WebMatrix.WebData.WebSecurity.CurrentUserId;

                    LogTypeDA.Update(tblLogType);
                    return RedirectToAction("LogTypeIndex");
                }
            }
            catch (DataException)
            {
                //Log the error (add a variable name after DataException)
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }
            return View(LogType);
        }
    }
}

Here is the general class function in controller :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using i_insurance.Models;
using i_insurance.DataAccess;
using System.Data;

namespace i_insurance
{
    public class HelperController : Controller
    {

        public static IEnumerable<SelectListItem> GetAllRecStatus()
        {
            var recStatusDA = new RecStatusDA();
            IEnumerable<SelectListItem> slItem = from s in recStatusDA.GetAll()
                                                 select new SelectListItem
                                                 {
                                                     Text = s.RecStatusName,
                                                     Value = s.RecStatusId.ToString()
                                                 };

            return slItem;
        }

    }
}

Here is the View LogTypeCreate.cshtml code to create new LogType data:

@model i_insurance.Models.LogTypeModel.LogType

@{
    ViewBag.Title = "Create New Log Type";
}

<h2>@ViewBag.Title</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.AntiForgeryToken()
    @Html.ValidationSummary()

    <fieldset>
        <legend>Log Type</legend>

        <br />
        <br />

        <table>
            <tr>
                <td>@Html.LabelFor(model => model.LogTypeCode)</td>
                <td>:</td>
                <td>
                    @Html.EditorFor(model => model.LogTypeCode)
                    @Html.ValidationMessageFor(model => model.LogTypeCode)
                </td>
            </tr>
            <tr>
                <td>@Html.LabelFor(model => model.LogTypeName)</td>
                <td>:</td>
                <td>
                    @Html.EditorFor(model => model.LogTypeName)
                    @Html.ValidationMessageFor(model => model.LogTypeName)
                </td>
            </tr>
            <tr>
                <td>@Html.LabelFor(model => model.LogTypeDecr)</td>
                <td>:</td>
                <td>
                    @Html.EditorFor(model => model.LogTypeDecr)
                    @Html.ValidationMessageFor(model => model.LogTypeDecr)
                </td>
            </tr>
            <tr>
                <td>@Html.LabelFor(model => model.RecStatusId)</td>
                <td>:</td>
                <td>
                    @*@Html.DropDownListFor(model=>model.RecStatusId, new SelectList(ViewBag.RecStatusList,"RecStatusId","RecStatusName"))*@
                    @Html.DropDownListFor(model => model.RecStatusId, Model.RecordStatusList)
                    @Html.ValidationMessageFor(model => model.RecStatusId)
                </td>
            </tr>
        </table>


        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "LogTypeIndex")
</div>

My question how to make this mvc view support dropdownlist from reference table tblRecStatus ?

With 
BindText  = tblRecStatus.RecStatusName
BindValue = tblRecStatus.RecStatusId (0  = dis active, 1 = active)

Example :
Dropdownlist will contain
 - Dis Active
 - Active

if user choose Active, it will save value 1 for column tblLogType.RecStatusId

Thank You.

I already test solution from @Motomoto Pink, and it worked for dropdownlist and still have issue when i try to create new data or update data logType with leave all field blank

Here is the error code :

The ViewData item that has the key 'RecStatusId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'. 

Source Error :

@Html.DropDownListFor(model => model.RecStatusId, Model.RecordStatusList)

Source File: d:\Projects\VS2012\Website\i_insurance\i_insurance\Views\LogType\LogTypeUpdate.cshtml    Line: 48 

Stack Trace:

[InvalidOperationException: The ViewData item that has the key 'RecStatusId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.]
   System.Web.Mvc.Html.SelectExtensions.GetSelectData(HtmlHelper htmlHelper, String name) +355
   System.Web.Mvc.Html.SelectExtensions.SelectInternal(HtmlHelper htmlHelper, ModelMetadata metadata, String optionLabel, String name, IEnumerable`1 selectList, Boolean allowMultiple, IDictionary`2 htmlAttributes) +142
   System.Web.Mvc.Html.SelectExtensions.DropDownListFor(HtmlHelper`1 htmlHelper, Expression`1 expression, IEnumerable`1 selectList, String optionLabel, IDictionary`2 htmlAttributes) +94
   System.Web.Mvc.Html.SelectExtensions.DropDownListFor(HtmlHelper`1 htmlHelper, Expression`1 expression, IEnumerable`1 selectList) +60
   ASP._Page_Views_LogType_LogTypeUpdate_cshtml.Execute() in d:\Projects\VS2012\Website\i_insurance\i_insurance\Views\LogType\LogTypeUpdate.cshtml:48
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +103
   System.Web.WebPages.StartPage.RunPage() +17
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +62
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +23
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +245
   System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +22
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +245
   System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +22
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +176
   System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +75
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +99
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9634212
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

2 Answers 2

1

First you have to create DataAccess for tblRecStatus table to get all data from tblRecStatus (Maybe you already have it)

public class RecStatusDA : BaseDA
{
    public List<tblRecStatus> GetAll()
    {
       return (from tblRecStatus s in this.DataContext.tblRecStatus
                    select s).ToList();
    }
}

Next, add one more properties into LogTypeModel.LogType class for manage data from tblRecStatus

namespace i_insurance.Models
{
    public class LogTypeModel
    {
        public class LogType
        {
         ...
         public IEnumerable<SelectListItem> selectList { get; set; }
        }
        ...
    }
}

In the Controller, LogTypeController, you have to bind data to DropDownList at method LogTypeCreate (which is not HttpPost method), see the code below:

private IEnumerable<SelectListItem> GetAllRecStatus()
{
    var recStatusDA = new RecStatusDA();
    IEnumerable<SelectListItem> slItem = from s in recStatusDA.GetAll()
                                            select new SelectListItem
                                            {
                                                Selected = s.RecStatusId.ToString() == "default value you want to set"
                                                Text = s.RecStatusName,
                                                Value = s.RecStatusId.ToString()
                                            };
    return slItem;
}

public ActionResult LogTypeCreate()
{
    var model = new LogTypeModel.LogType { selectList = GetAllRecStatus() };
    return View(model);
}

In the View LogTypeCreate.cshtml, define the DropDownList

<tr>
   <td>Status</td>
   <td>:</td>
   <td>
        @Html.DropDownListFor(model => model.RecStatusId, Model.selectList)
   </td>
</tr>

Final, see in the LogTypeCreate (HttpPost method), you could set selected ResStatusId to tblLogType.RecStatusId

tblLogType.RecStatusId = LogType.RecStatusId;
Sign up to request clarification or add additional context in comments.

12 Comments

Hi Motomoto, i try something new when i create new LogType in page LogTypeCreate.cshtml and fill blank in all field then press button create this error appear in @Html.DropDownListFor(model => model.RecStatusId, Model.RecordStatusList) error info : The ViewData item that has the key 'RecStatusId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'. why this happen and how i can fix this one ? , thank
Could I see your new LogType to investigate this?
Yes you can, i already updated the code in my main question, and how i can set the default value for dropdownlist record status when i create new data [i want to set the active value in dropdownlist]?
Yes, you can set the default select value, see in LogTypeController code, I updaed my answer.
I alredy try to add code in my controller Selected = s.RecStatusId.ToString() but selected is bool property, it generate error when i add that code. And how about the error when i submit new blank data in @Html.DropDownListFor ?
|
0

You will need to specify a collection in your model which contains all the elements of the drop down list.

prop List<TblRecStatus> StatusList {get; set;}

Then in your view just do this

@Html.DropDownListFor(m => m.StatusList, new SelectList(StatusList, "StatusID", "StatusName"))

1 Comment

Hi Gjohn, i already updated my LogTypeModel, and updated my view base on your suggestion, but i get this error : Error 1 The name 'StatusList' does not exist in the current context in VS indicator it error in this code: new SelectList(StatusList, StatusList seem not available, is there other requirement for this ?

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.