Archive for category MVC

Templates can be used only with field access… error using ToShortDateString()

While binding a partial view to a model, I noticed the my nullable DateTime field was showing the time portion. Adding attributes to the model didn’t work, so I attempted to use the ToShortDateString() method:

@Html.TextBoxFor(model => Model.StartDate.Value.ToShortDateString(), new { @class = “form-control”, @maxlength = “10” })

However, this caused the error “Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions”.

To get around this, set the shortened date value to a string, and used that as the binding to the textbox:

var startDate = Model.StartDate.Value.ToShortDateString();

@Html.TextBoxFor(model => startDate, new { @class = “form-control”, @maxlength = “10” })

Advertisements

Leave a comment

HTTP Error 403.14 for MVC site

I was setting up a new MVC 5 site on a Windows Server 2016 Datacenter machine when I ran into this error:

HTTP Error 403.14 – Forbidden – The Web server is configured to not list the contents of this directory.

I didn’t actually want the web server to list the contents, so that was not the problems.

This fancy Internet thing had lots of suggestions, the best ones at Stack Overflow. However, those didn’t solve my problem. What did solve my problem was to correct a dumb mistake. Here was my IIS configuration:

IIS

 

 

 

You’ll notice the ever-populate “ScottSite” is looking like a sad, plain folder. And that was my problem – I hadn’t turned it into an application. Right-clicking on my non-application and selecting “Convert to application” fixed my problem. Magic.

IIS

 

 

 

Leave a comment

The MVC model is null when posting

I had an MVC view that I was using to update my data using a POST method by using a Bootstrap modal popup window. Everything seemed fine, but when I put a breakpoint in my controller action, my model was null. My very simple action:

       [HttpPost]
       public ActionResult Update(Coaster model) {
           return View();
       }

I’m going to give away the ending. The problem was that my form didn’t have the “name” property attached to the “input” tag. I thought the “id” property would be enough to send my model from the view to the controller, but it wasn’t. So instead of this:

<input type="text" id="Code" class="form-control" />

I had to have this:

<input type="text" id="Code" name="Coaster" class="form-control" />


			

Leave a comment

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 () {
        $("#Date").datepicker({
            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:

    $.ajax({
        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) {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                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
         GlobalConfiguration.Configure(WebApiConfig.Register);
     }

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:

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

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) {
 $("#id").val(id);
 $('#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);
}

Fixed!

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"]
     .Split(',').ToList());

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

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

Leave a comment