Archive for category MVC

Is user logged in to .NET Core MVC view?

If you are in a .NET Core MVC view and need to know if a user is logged-in, use the “User.Identity.IsAuthenticated” property:

@if (User.Identity.IsAuthenticated) {
    <input type="button" id="submit" value="Submit"  />
}

Leave a comment

Getting around the “parameters dictionary contains a null entry” error in MVC

I had a rather simple GET controller on my MVC application that was used to reset a password. There were two ResetPassword controller, the other for a POST request. My GET request took a couple of fields and returned a model – pretty simple:

public ActionResult ResetPassword(string email, Guid uniqueId) {
  if (uniqueId.HasValue) {
    ResetPassword model = new ResetPassword() {
        EmailAddress = email,
        UniqueId = uniqueId
    };
  }
      return View(model);
    }

This worked if the user used the screen the proper way, coming from a link sent in an e-mail. However, we know that sometimes users don’t do things the right way, and if they came to the link by typing in the URL, they would get an ugly, semi-offensive message:

The parameters dictionary contains a null entry for parameter ‘uniqueId’ of non-nullable type ‘System.Guid’ for method ‘System.Web.Mvc.ActionResult ResetPassword(System.String, System.Guid)’ in ‘Coasters.Controllers.HomeController’. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters

So, I though I would just add an empty controller action to handle these situations:

public ActionResult ResetPassword() {
    return View();
}

Nope:

The current request for action ‘ResetPassword’ on controller type ‘HomeController’ is ambiguous between the following action methods:
System.Web.Mvc.ActionResult ResetPassword() on type Coasters.Controllers.HomeController
System.Web.Mvc.ActionResult ResetPassword(System.String, System.Guid) on type Coasters.Controllers.HomeController

I’m not a routing genius (or even a routing AP student, or a routing C-student), so instead of adjusting the routing to handle this, I made an adjustment to the controller action, change the Guid to a nullable Guid, and that resolved my issue:

public ActionResult ResetPassword(string email, Guid? uniqueId) {
    ResetPassword model = null;

    if (uniqueId.HasValue) {
        model = new ResetPassword() {
          EmailAddress = email,
          UniqueId = uniqueId.Value
       };
    }

    return View(model);
}

Leave a comment

Missing hidden variables when posting in MVC

I had a simple ASP.NET MVC form that was posting to my controller action, but the hidden variable wasn’t posting. Here is my very simple form:

@using (Html.BeginForm()) {

@Html.TextAreaFor(model => model.CoasterText, new { @class = “form-control”, @cols = “20”, @rows = “15” })

</div>

 

</div>
</div>
}

@Html.HiddenFor(model => model.CoasterId)

The text value was being posted to the controller, but no the CoasterId. And the reason for that is that I had defined my hidden variable outside of the form. Oops. Easy fix – I just had to move the variable inside the closing curly brace.

Leave a comment

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” })

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" })

1 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