Disable Html.DropDownListFor if only one item in dropdown


@Html.DropDownListFor(m => m.SelectedValue,
new SelectList(Model.CollectionOfItemsForDropdown, "ValueField", "NameField"),
@Model.CollectionOfItemsForDropdown.Count > 1
? (object)new { @class = "form-control", required = "true", }
: new { @class = "form-control", required = "true", disabled = "disabled" })

You have to use the conditional operator here for the anonymous objects because the dropdown list will be disabled if the word ‘disabled’ is rendered in the tag in any way.

NHibernate Session Manager needs HttpContext for NUnit testing

In a codebase I work in, NHibernate needs an HttpContext to get its current session – like this:


public static ISession GetCurrentSession()
{
var context = HttpContext.Current;
var currentSession = context.Items[CurrentSessionKey] as ISession;
...

To get my hands on a session for a NUnit test – I put this in the setup:


HttpContext.Current = new HttpContext(
new HttpRequest(null, "http://tempuri.org", null),
new HttpResponse(null));

 

Also, I wipe the context in the teardown:

<code>

[TearDown]
public void TearDown()
{
HttpContext.Current = null;

}

</code>

Credit for this goes to :

http://caioproiete.net/en/fake-mock-httpcontext-without-any-special-mocking-framework/

Downloading a file from MVC controller to .ascx using javascript ajax

Here is a simple way to download a file to a .net user control from a newer MVC controller.

The Controller code:

public FileResult DownloadSweetFile()
{
var downloadDirectory = _appSettings.PathToFile;
var filePathAndName = Path.Combine(downloadDirectory, "MySweetFile.pdf");

var cd = new System.Net.Mime.ContentDisposition
{
FileName = "MySweetFile.pdf",
Inline = false, //NOTE: This forces always prompting the user to download, not open file in the browser
};
Response.AppendHeader("Content-Disposition", cd.ToString());

return File(filePathAndName, "application/pdf");
}

I used a button on the page to fire the javascript

button type="button" id="btnSweetDownload" onclick="downloadSweetFile();" Click here to download a Sweet File!
(I removed the button tag so this will show correctly)

And here is the javascript to use in the .ascx file:

function downloadSweetFile() {
var url = '/MyControllerName/DownloadSweetFile';
window.location = url;
};

Refactoring – or Code Remodeling

I think that most days, code remodeler would be the right job title for a lot of us. We take working code and just make it better working code.

The book that got me started thinking of myself as a ‘code remodeler’ is Refactoring: Improving the Design of Existing Code by Martin Fowler.

If you haven’t read it, go get it quick! (Of course, and then read it…) Fowler lays out refactoring techniques in a straightforward way. You can start applying it immediately. I use Replace magic number with symbolic constant and Extract Method almost every day when I am helping a team with an older codebase.

Thanks for stopping by, and happy coding,

-Jim

Sending messages from an MVC Controller to toastr.js

Toastr and MVC controllers

I often want to generate a message in an .Net MVC controller class and present that to the user with toastr.
Here is a nice pattern for doing just that using TempData.

The Javascript

In a javascript file that is accessible to all the views that are using toastr:

$(document).ready(function() {
if ($('#success').val()) {
displayMessage($('#success').val(), 'success');
}
if ($('#info').val()) {
displayMessage($('#info').val(), 'info');
}
if ($('#warning').val()) {
displayMessage($('#warning').val(), 'warning');
}
if ($('#error').val()) {
displayMessage($('#error').val(), 'error');
}
});

var displayMessage = function (message, msgType) {
toastr.options = {
“closeButton”: false,
“debug”: false,
“positionClass”: “toast-top-right”,
“onClick”: null,
“showDuration”: “300”,
“hideDuration”: “1000”,
“timeOut”: “8000”,
“extendedTimeOut”: “1000”,
“showEasing”: “swing”,
“hideEasing”: “linear”,
“showMethod”: “fadeIn”,
“hideMethod”: “fadeOut”
};

toastr[msgType](message);
};

The Layout or Master Page

If you are using razor with mvc, you can put this in your _layout:

@Html.Hidden(“success”,@TempData[“success”])
@Html.Hidden(“info”,@TempData[“info”])
@Html.Hidden(“warning”,@TempData[“warning”])
@Html.Hidden(“error”,@TempData[“error”])

On my current project, I am working on an older mixed webforms and mvc site so I put this in the views:

<input type="hidden" value="<%=TempData["success"]%>" id="success" />
<input type="hidden" value="<%=TempData["info"]%>" id="info" />
<input type="hidden" value="<%=TempData["warning"]%>" id="warning" />
<input type="hidden" value="<%=TempData["error"]%>" id="error" />

The Controller Code

You send information back from the controller like this:

TempData["warn"] = "You must see this amazing information in a toast!!!";

Javascript get sending element in all browsers

   function mySweetClickEvent(event) {

        event = window.event || event; //NOTE: another lovely hack to make Firefox work…

        var target = event.target ? event.target : event.srcElement; //NOTE: another lovely hack to make IE work

        var senderToUse;

        if (target) {

            senderToUse = target; //this works for ie and chrome

        } else {

            senderToUse = event; //this works for firefox

        }

…do stuff with the sender here…

}

CSS to replace cellpadding and cellspacing

I was having trouble properly formatting a table in html with css and I found this on Stack Overflow.

Replace cellpadding with:

th, td { padding: 5px; }

Replace cellspacing with:

table { border-collapse: separate; border-spacing: 5px; } // cellspacing=”5″
table { border-collapse: collapse; border-spacing: 0; } // cellspacing=”0″

Replace valign with:
th, td { vertical-align: top; }

Replace align (center) with:
table { margin: 0 auto; }

The original article is here.