Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8419841
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T02:43:34+00:00 2026-06-10T02:43:34+00:00

I have a drop down list written in Razor for a MVC app I

  • 0

I have a drop down list written in Razor for a MVC app I am working on as:

@Html.DropDownList("BillId", "")

However the user does not have to select anything according to the logic of my program (the list is populated with ‘Bill’ objects in my controller). If they do not select any thing I get an error

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

How do I write a statement in Razor to return a BillId of 0 if nothing is selected?

I am not sure of the syntax as I have a background in straight java and VB but something alongs the line of

 If DropdownBox.SelectedIndex = 0
 Else 
 BillId = DropdownBox.SelectedIndex
 End

Controller as follows:

Function Create(id As Integer) As ViewResult
        ViewBag.id = id
        Dim job As Job = New Job
        job.CustomerId = id
        job.JobAmount = 0
        job.JobDate = Date.Now()
        job.JobStatus = "Active"

        Dim BillList = New List(Of Bill)()

        Dim BillQuery = From s In db.Bills
                        Select s

        BillList.AddRange(BillQuery)

        ViewBag.BillIdList = New SelectList(BillList, "BillId", "BillDate")

        ViewBag.BillId = New SelectList(BillList, "BillId", "BillDate")

        Return View(job)
    End Function

The POST function for create is as below:

    <HttpPost()>
    Function Create(job As Job) As ActionResult
        If ModelState.IsValid Then
            db.Jobs.Add(job)
            db.SaveChanges()

            Dim customer As Customer = db.Customers.Find(job.CustomerId)
            Dim customerNumber As String = customer.CustCellphone.ToString()
            Dim messageSender As SendMessage = New SendMessage
            Dim smsMessage As String = "LAUNDRY: Job Number " & job.JobId & " has been booked in. You will be notified when individual services within it are ready for collection."
            messageSender.SendMessage(smsMessage, customerNumber)

            Dim url As String = "/RequestedService/AddService/" + job.JobId.ToString()
            Return Redirect(url)
        End If
        Return View(job)
    End Function

EDIT

I was wondering too how this is passed back as in the POST I may be able to check for a ‘null’? However I feel the problem may be the moment the submit button is pressed

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T02:43:36+00:00Added an answer on June 10, 2026 at 2:43 am

    In your POST controller action you forgot to populate the ViewCrap (oops, I meant ViewBag) before returning the view:

    <HttpPost()>
    Function Create(job As Job) As ActionResult
        If ModelState.IsValid Then
            ...
        End If
    
        ' Here you must populate the ViewCrap before returning the view the same 
        ' way you did in your GET action because your view depend on it
        Dim BillQuery = From s In db.Bills
                        Select s
        ViewBag.BillId = New SelectList(BillQuery.ToList(), "BillId", "BillDate")
    
        Return View(job)
    End Function
    

    But I would hyper strongly recommend you to use view models and forget about the existence of the …… (the word that I don’t want to pronounce).


    UPDATE:

    Now let’s look at the correct way to implement this (which is by using view models). A view model is a class that you should define for each of your views and which will represent its specific requirements. So from what you have said in the comments section to my answer you want to have a dropdown list in your view where the user has to select a bill from a dropdown and which is required.

    So let’s roll the view model:

    public class JobViewModel
    {
        [Required(ErrorMessage = "Please select a bill")]
        [Display(Name = "Bill")]
        public int? SelectedBillId { get; set; }
        public IEnumerable<SelectListItem> Bills 
        { 
            get 
            {
                return db.Bills.ToList().Select(x => new SelectListItem
                {
                    Value = x.BillId.ToString(),
                    Text = x.BillDate.ToString()
                });
            } 
        }
    
        public int CustomerId { get; set; }
    
        ... here you could put any other properties that you want 
            to display on the view, things like JobId, ...
    }
    

    then we define our controller with the 2 actions:

    public ActionResult Create(int id)
    {
        var model = new JobViewModel
        {
            CustomerId = id
        };
        return View(model);
    }
    
    [HttpPost]
    public ActionResult Create(JobViewModel model)
    {
        if (ModelState.IsValid)
        {
            // Using AutoMapper here to map between the domain model
            // and the view model (http://automapper.org/)
            var job = Mapper.Map<JobViewModel, Job>(model);
    
            // Now call your service layer to do the necessary processings
            // on this job domain model including saving the job and sending 
            // messages and stuff. This avoids polluting your controller with
            // business logic code which belongs to your service layer
            ServiceLayer.ProcessJob(job);
    
            return RedirectToAction("AddService", "RequestedService", new { id = job.JobId });
        } 
    
        return View(model);
    }
    

    and finally you will have a corresponding view which will be strongly typed to the view model:

    @model JobViewModel
    
    @using (Html.BeginForm())
    {
        <div>
            @Html.LabelFor(x => x.SelectedBillId)
            @Html.DropDownListFor(x => x.SelectedBillId, Model.Bills, "-- select --")
            @Html.ValidationMessageFor(x => x.SelectedBillId)
        </div>
    
        ... some other input fields
    
        <p><button type="submit">OK</button></p>
    }
    

    And now, as promised in the comments section let me show what I dubbed the absolute pornographic approach to solve this and which if you implemented in your application I will have to ask you to no longer come back and ask any ASP.NET MVC related question on StackOverflow 🙂

    The pornographic approach consisted into manually inserting an item with id = 0 and text = empty string into the beginning of the list and then inside the controller verifying if the selected id equals 0 in order to check whether the model is valid or not:

    So in your GET action:

    Function Create(id As Integer) As ViewResult
        ViewBag.id = id
        Dim job As Job = New Job
        job.CustomerId = id
        job.JobAmount = 0
        job.JobDate = Date.Now()
        job.JobStatus = "Active"
    
        Dim Bills = db.Bills.ToList().Select(Function(s) New SelectListItem With { .Value = s.BillId.ToString(), .Text = s.BillDate.ToString() })
        Bills.Insert(0, New SelectListItem With { .Value = "0", .Text = "" })
        ViewBag.BillId = Bills
    
        Return View(job)
    End Function
    
    <HttpPost()>
    Function Create(job As Job, BillId as Integer) As ActionResult
        If BillId > 0 Then
            db.Jobs.Add(job)
            db.SaveChanges()
    
            Dim customer As Customer = db.Customers.Find(job.CustomerId)
            Dim customerNumber As String = customer.CustCellphone.ToString()
            Dim messageSender As SendMessage = New SendMessage
            Dim smsMessage As String = "LAUNDRY: Job Number " & job.JobId & " has been booked in. You will be notified when individual services within it are ready for collection."
            messageSender.SendMessage(smsMessage, customerNumber)
    
            Dim url As String = "/RequestedService/AddService/" + job.JobId.ToString()
            Return Redirect(url)
        End If
        ModelState.AddModelError("BillId", "Please select a bill")
        Return View(job)
    End Function
    

    and inside the view:

    @Html.DropDownList("BillId")
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a drop-down list hardcoded in an MVC View User Control page and
I have written a cascading drop down list using JQuery. The code that I
I have written some code for displaying a drop down list, but the code
I have written a web page that provides a drop down list of reports
I have a webpage written in HTML. I have a dropdown list that is
I have one drop down list in my page, which contains two options. What
I have a drop-down list which is generated based on the following sql query:
I have a drop down list where users can select a theme for the
I have a drop down list that has options that need to be passed
I have a drop down list that triggers an updatepanel when the index is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.