Archive for category MVC

jQuery DatePicker – Removing time from a DatePicker control

I had an MVC view with a TextBox control binding to a model property

@Html.TextBoxFor(model => model.Date, String.Empty, new { @class = "form-control" })

This control was bound to a jQuery DatePicker control:

    $(document).ready(function () {
            minDate: 0

My problem was that when the model was bound from the database, the DatePicker would also show the time, not just the date like I wanted:









The fix for this is to make the second parameter a format string with only the date:

@Html.TextBoxFor(model => model.IssueDate, "{0:d}", new { @class = "form-control" })

Leave a comment

Web API getting 404

When trying to perform a simple GET request using Web API in my MVC application, I was getting a 404 message. I was accessing it through Ajax, and the URL was correct:

        url: 'http://localhost:1234/api/UserApi',
        type: 'GET',
        cache: false,
        contentType: 'application/json'

The problem was actually environmental. At a particular job site, the machines were locked down, including not being able to run PowerShell command – thus, an impediment to using NuGet. So I had to do several things to get my project working, but hopefully, if you’re having a similar issue, one of these is the key for you.

Several DLLs needed to be replaced, as the version were too old:

  • System.Net.Http
  • System.Net.Http.Formatting
  • System.Web.Http

The WebApiConfig.cs file was missing from the App_Start folder, so I added it:

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

namespace ScottProject.App_Start {
    public class WebApiConfig {
        public static void Register(HttpConfiguration config) {

                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }

The Global.ascx.cs file was missing the referene to the WebApiConfig file:

     protected void Application_Start() {
         // Other file snipped out

So this particular situation was specific to my situation, but perhaps one of those issues will help someone else.

Leave a comment

When your Boolean parameter says “oncheck” in JavaScript and what to do about it

In my MVC application, I was building a table using a partial view. One column was an HTML link whose onclick event was bound to the “show” method, and this method took two parameters, a string and a boolean:

      <td><a onclick="show('@item.ID', '@item.IsVisible')">Click Me!</a></td>

Inside the “show” method, notice the “visible” checkbox. I am simply setting the “checked” property to true or false, depending on the value of the “visible” parameter:

function show(id, visible) {
 $('#visible').prop('checked', visible);

When running this code, I got strange behavior, and using the Developer Tools (F12 in IE), I noticed that the string generating the edit button line looked like this:

 <td><a onclick="show('1', 'checked')">Click Me!</a></td>

Huh. How did that “checked” get in there? When I ran the debugger, and MVC code was correctly binding the Boolean variable to either “True” or “False”, so what’s with this “checked” things I’m seeing?

There were two problems here. First, I needed to modify the MVC code, calling the “ToString” method on the Boolean property:

    <td><a onclick="show('@item.ID', '@item.IsVisible.ToString()')">Click Me!</a></td>

Second, this would return “True” or “False”, with the first letter capitalized. JavaScript needs those values in lower case. So I set up a ternary operator to handle that:

function show(id, visible) {
  $('#visible').prop('checked', visible == "True" ? true : false);


Leave a comment

Converting a List of strings to a SelectList

I had a brief list of comma-separated strings that I was storing in the web.config file, and I needed to convert them into a SelectList to bind to a DropDownListFor control in MVC. For that, there was a very simple method:

TempData["FundingTypes"] = new SelectList(ConfigurationManager.AppSettings["CoasterTypes"]

If I had needed a List<SelectListItem> instead, I would have done this:

            TempData["FundingTypes"] = ConfigurationManager.AppSettings["CoasterTypes"]
                .Select(f => new SelectListItem() {
                    Text = f.ToString(),
                    Value = f.ToString()

Leave a comment

Showing MVC ModelState errors in the view

I wanted to show the various ModelState errors encountered in an MVC controller and display them in the view. So in my controller, I have a bit of code that loops through the errors and builds them in a string, adding an HTML line break between each error:

string errors = String.Empty;

foreach (ModelState modelState in ViewData.ModelState.Values) {
     foreach (ModelError error in modelState.Errors) {
          errors += “<br />” + error.ErrorMessage;

ViewBag.Message = “The following errors have occurred: “ + errors;

In the view, I show my ViewBag variable. Notice that I use the Html.Raw method to display the HTML code properly in using Razor:



Leave a comment

HTML select value missing from MVC model after post

In my MVC project, I have a property that is either Y or N. No maybe, no empty string – “Y” or “N”.

public class Coaster {
     public string DoYouLikeCoasters { get; set; }

I first thought just to do a basic select element. Something simple:

<select id=”DoYouLikeCoasters”>
     <option value=”Y”>Y</option>
     <option value=”N”>N</option>

But when I checked the model in the controller after the form was posted, the “DoYouLikeCoasters” property was empty. I basically hadn’t told MVC that I wanted the property. In order to properly get the value to the controller, I needed to MVC-ify the select by using the Html.DropDownListFor. Since I just wanted “Y” and “N” as values, I still wanted to essentially hard-code the values. So here is how I did that:

@Html.DropDownListFor(model => model.DoYouLikeCoasters, new SelectListItem[] {
     new SelectListItem() { Value = “Y”, Text = “Y” },
     new SelectListItem() { Value = “N”, Text = “N” }
}, new { @class = “form-control”, @style = “width: 50px” })

Leave a comment

Defining a method in a view

I know there will be much gnashing of teeth from MVC purists for even thinking about designing a view this way, but if you need to define a method inside a view, you can do it like I show below. In this instance, I am writing a method that will take a date, determine if it is null, and return either the short date or an empty string:

First, the method, defined at the top of the view:

 var getDate = new Func<DateTime, string>((date) => date != DateTime.MinValue ? date.ToShortDateString() : String.Empty);

And then calling the method:

@foreach (Models.Coaster item in Model.Coasters) {

Leave a comment