Populate drop down list from FieldValue database table

thgtang

New member
Joined
Nov 13, 2019
Messages
4
Programming Experience
1-3
I have a database table called FieldValue to store all the drop down list item and its option. It has 3 fields, fieldname, fieldvalu, fieldvaludesc, the fieldvaludesc is the option shown in the drop down list.

I have two models called ContactRecord and FieldValue, one of the fields MsgType will be shown in form of drop down list and its option is referring to the FieldValue table where FieldName = "MsgType"

FieldValue.cs
C#:
public class FieldValue
    {
        public string FieldName { get; set; }
        public string FieldVal { get; set; }
        public string FieldValueDesc { get; set; }
        public char DefaultValue { get; set; }
    }

ContactRecord.cs

C#:
public partial class ContactRecord
    {
        public long ContactId { get; set; }

        [Required(ErrorMessage = "Please enter your name."), MaxLength(50)]
        [Display(Name = "Name")]
        public string SenderName { get; set; }
        [Required(ErrorMessage = "Please select the Message Type")]
        [Display(Name = "Message Type")]
        public string MsgType { get; set; }
        [Required(ErrorMessage = "Please enter the Subject.")]
        public string Subject { get; set; }
        [Required(ErrorMessage = "Please enter your email.")]
        [DataType(DataType.EmailAddress, ErrorMessage = "E-mail is not valid")]
        public string Email { get; set; }
        public string Status { get; set; }
    }

In the ContactRecordController, I have created the following code
C#:
public ContactRecordsController(theManagerContext context)
        {
            _context = context;
        }

        // GET: ContactRecords
        public async Task<IActionResult> Index()
        {
            return View(await _context.ContactRecord.ToListAsync());
        }

        private void PopulateMsgTypes(object selectedMsgType=null)
        {
            var MsgTypeQuery = from p in _context.FieldValue
                                orderby p.FieldValueDesc
                                select p;
            ViewBag.FieldName = new SelectList(MsgTypeQuery, "FieldName", "FieldValueDesc", selectedMsgType);                 
        }

    

        // GET: ContactRecords/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: ContactRecords/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("ContactId,SenderName,MsgType,Subject,Email,ContactNo,CreateTime,FollowedUpBy,Status")] ContactRecord contactRecord)
        {
            if (ModelState.IsValid)
            {
                _context.Add(contactRecord);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
           PopulateMsgTypes("MsgType");
            return View(contactRecord);
        }

In the Create.cshtml, I have no idea what to input in the asp-items. would anyone give me some advices, please?
C#:
<div class="form-group">
                <label asp-for="MsgType" class="control-label"></label>
                <select asp-for="MsgType" asp-items="??" class="form-control" />
                <span asp-validation-for="MsgType" class="text-danger"></span>
            </div>

Thank you for your help.
 
You put the items into ViewBag.FieldName so that's where you get them from again, so that's what you put in that attribute.

You really ought to change that name though. Every name should describe what it is for. Does FieldName reflect what that dynamic property is for? No, it does not. A more appropriate name would be MessageTypes.

I have to say, I also think that the way you've designed that database and the correpsonding entities is rather dodgy. Personally, I'd have a MessageType table with MessageTypeId and Description columns then a Contact entity would have a MessageTypeId foreign key. I'd have similar separate tables for all such reference lists. Grouping unrelated reference lists together like that is a false economy, in my opinion.
 
Thanks for your answer.

Actually I have thought about that. As I get several forms and if I create a table for each drop down list, I am not sure if it's a good design and will be hard to manage.

or is it simpler if I put the MsgType options in the code?
 
It's hard to say for sure without knowing all the details but, 99 times out of 100, I'd be creating a separate table for each list and then storing foreign keys in the related records. It might seem like more effort but that's just because everything seems hard and lots of them together seems really hard. Managing a foreign key relation is simple, which you'll soon come to realise, and managing several of them is also simple. Better to start with a good design and grow into it than start with something dodgy because it seems easier and regret it later.
 
Back
Top Bottom