Click here to Skip to main content
15,868,004 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a form having a drop down list "MsgType" which will retrieve its option from database table "DDLMsgType".

The web form is created by scaffolding the ContactRecord model which also contain the MsgType.

I tried to populate the MsgType to the MsgType form but my code does not work. I would like to ask what I have missed. Thanks.

<div class="form-group">
             <label asp-for="MsgType" class="control-label"></label>
             <select asp-for="MsgType" asp-items="Model.MsgTypeSL" class="form-control" />
             <span asp-validation-for="MsgType" class="text-danger"></span>
         </div>


What I have tried:

DDLMsgType.cs
public class DDLMsgType
       {
           public int MsgTypeID { get; set; }
           public string MsgType { get; set; }
           public string MsgTypeStatus { get; set; }

       }


ContactRecord.cs
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; }
public SelectList MsgTypeSL { get; set; }



public class ContactRecordsController : Controller
    {
        private readonly theManagerContext _context;

        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.DDLMsgType
                                orderby p.MsgType
                                select p;
            
        }

     
        // 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));
            }

            return View(contactRecord);
        }

        // GET: ContactRecords/Edit/5
        public async Task<IActionResult> Edit(long? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var contactRecord = await _context.ContactRecord.FindAsync(id);
            if (contactRecord == null)
            {
                return NotFound();
            }
            PopulateMsgTypes("MsgType");
            return View(contactRecord);
        }
Posted
Updated 14-Nov-19 4:31am
v4
Comments
ZurdoDev 11-Nov-19 9:40am    
I do not understand what you are asking us.

1 solution

First of all, don't add the SelectList to your database entity. At best, it will be ignored; otherwise, it will generate errors because Entity Framework doesn't understand how to store or load it.

I would recommend using a view-model to serve as the model for your view. Add the SelectList to the view-model. Write a method to populate the SelectList, and call it before displaying your create or edit view.

Database entity:
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; }
}
View model:
C#
public class ContactRecordViewModel
{
    public ContactRecordViewModel(ContactRecord record)
    {
        ContactId = record.ContactId;
        SenderName = record.SenderName;
        MsgType = record.MsgType;
    }
    
    public ContactRecordViewModel()
    {
    }
    
    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; }
    
    public SelectList MsgTypeSL { get; set; }
    
    public void UpdateModel(ContactRecord record)
    {
        record.SenderName = SenderName;
        record.MsgType = MsgType;
    }
}
Controller:
C#
private async Task PopulateLookups(ContactRecordViewModel model)
{
    var msgTypes = _context.DDLMsgType.OrderBy(p => p.MsgType).ToListAsync();
    model.MsgTypeSL = new SelectList(msgTypes, nameof(DDLMsgType.MsgType), nameof(DDLMsgType.MsgType), model.MsgType);
}

[HttpGet]
public async Task<IActionResult> Create()
{
    var model = new ContactRecordViewModel();
    await PopulateLookups(model);
    return View(model);
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(ContactRecordViewModel model)
{
    if (!ModelState.IsValid)
    {
        await PopulateLookups(model);
        return View(model);
    }
    
    var record = new ContactRecord();
    model.UpdateModel(record);
    _context.ContactRecord.Add(record);
    await _context.SaveChangesAsync();
    return RedirectToAction(nameof(Index));
}

[HttpGet]
public async Task<IActionResult> Edit(long id)
{
    var record = await _context.ContactRecord.FindAsync(id);
    if (record is null) return NotFound();
    
    var model = new ContactRecordViewModel(record);
    await PopulateLookups(model);
    return View(model);
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(ContactRecordViewModel model)
{
    var record = await _context.ContactRecord.FindAsync(model.ContactId);
    if (record is null) return NotFound();
    
    if (!ModelState.IsValid)
    {
        await PopulateLookups(model);
        return View(model);
    }
    
    model.UpdateModel(record);
    await _context.SaveChangesAsync();
    return RedirectToAction(nameof(Index));
}

NB: Based on your DDLMsgType entity, it looks like the MsgType property in your ContactRecord should probably be an int linking to the MsgTypeID. In which case, you'll need to change the view-model to match, and change the dataValueField parameter to the SelectList constructor.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900