HTML Helper syntax issue

154 Views Asked by At

I have this piece of code in a couple of cshtml pages:

@model bt2.Models.ScheduleWork

@using System.Security.Claims;

@{
    bool Admin = User.IsInRole("Admin");
    var identity = (ClaimsIdentity)User.Identity;
    int Employee_ID = Int32.Parse(identity.FindFirst("DatabaseID").Value);
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

If I understand correctly, I should be able to turn this into a html helper. But I can't find the correct syntax.

I have created a cshtml called bthelper.cshtml and placed it in the App_Code folder

This was my first try:

@helper GetUserInfo() {
// Load user info into sever side variables for subsequent use
// Admin (true if an admin user)
// Employee_Id 
@using System.Security.Claims;

@{    
        bool Admin = (User.IsInRole("Admin"));
        var identity = (ClaimsIdentity)User.Identity;
        int Employee_ID = Int32.Parse(identity.FindFirst("DatabaseID").Value);
    }
}

Then my view cshtml became

@model bt2.Models.ScheduleWork

@bthelper.GetUserInfo()

@using (Html.BeginForm())
{
..........
....

When I run this I get

Unexpected "{" after "@" character. Once inside the body of a code block (@if {}, @{}, etc.) you do not need to use "@{" to switch to code.

With the highlight on the @{ line in the helper

So I tried all the permutations below, all with error messages

@helper GetUserInfo() {

@using System.Security.Claims;

bool Admin = (User.IsInRole("Admin"));
var identity = (ClaimsIdentity)User.Identity;
int Employee_ID = Int32.Parse(identity.FindFirst("DatabaseID").Value);
}

Unexpected "using" keyword after "@" character. Once inside code, you do not need to prefix constructs like "using" with "@".

Error on the @using line

@helper GetUserInfo() {

using System.Security.Claims;

bool Admin = (User.IsInRole("Admin"));
var identity = (ClaimsIdentity)User.Identity;
int Employee_ID = Int32.Parse(identity.FindFirst("DatabaseID").Value);
}

Namespace imports and type aliases cannot be placed within code blocks. They must immediately follow an "@" character in markup. It is recommended that you put them at the top of the page, as in the following example:

@using System.Drawing; @{ // OK here to use types from System.Drawing in the page }

Oh..... according to this my original syntax was actually correct

Can someone help me with the correct syntax? Razor syntax still confuses me. Contradictory error messages don't help

0

There are 0 best solutions below