ASP.NET MVC tip: C# functions in views – can it be done?
Posted: (EET/GMT+2)
So you've got a complex view in your ASP.NET MVC C# web application, and you need to set, say, the status of multiple input controls based on the model. Now, these kind of tasks often require you to write repetitive code inside your CSHTML view, but if you know you won't be needing the same code elsewhere, you might not endeavor to write a helper method.
But, if copy-paste programming isn't your thing (it certainly isn't mine), then you might want to try working with view functions. At this point, you might think: functions have no place in views!
Yes, you are right: functions have no place in views except when the function helps improve the code inside the view. For instance, I call a function inside a view justified, if 1) it makes the view cleaner and easier to maintain, and 2) the function in question is only useful inside the particular view and is only intended to help in view (HTML) generation.
With this in mind, here's how you'd define a view function in a .CSHTML file:
@functions {
public string NameAndCheck(string optionName, bool markChecked)
{
// generates the following HTML snippet: "name="option" checked"
// for use in a checkbox input field
string html = "name=\"" + optionName + "\"";
// has the option been selected?
if (markChecked)
{
html += " checked=\"checked\"";
}
return html;
}
}
Here, the key is the "@functions" declaration. It looks exactly like and a C# function/method declaration, and that's exactly what it is. To use this function elsewhere in the view, you could simply say:
<input type="checkbox" @Html.Raw(NameAndCheck("someName",
Model.SomeNameChecked))>
Hope this helps!