Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting error - Unexpected "if" keyword after "@" character. Once inside code, you do not need to prefix constructs like "if" with [duplicate]

Tags:

asp.net-mvc

im getting error in view- ""test1.cshtml"

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

test1.cshtml

    @model WebApplication9.Models.Names


@using (Html.BeginForm())
{
    @Html.TextBoxFor(m => m.MyName)

    <button type="submit">Submit</button>

    if (!string.IsNullOrWhiteSpace(Model.MyName))
    {
        <p>welcome, your name is @Model.MyName</p>
    }
}

controller code

 public ActionResult test1()
        {

            Names name = new Names();

            return View(name);

            ViewBag.Message = "Your contact page.";

            return View();
        }
        [HttpPost]
        public ActionResult test1(string name)
        {
            ViewBag.Message = "Hello what is ur name ???";
            ViewBag.Name = name;
            return View();
        }

model code

namespace WebApplication9.Models
{
    public class Names
    {
        public string MyName { get; set; }
    }
}
like image 603
STACK2 Avatar asked Apr 29 '16 13:04

STACK2


2 Answers

Try:

@model WebApplication9.Models.Names


@using (Html.BeginForm())
{
    @Html.TextBoxFor(m => m.Name)

    <button type="submit">Submit</button>

    if (!string.IsNullOrWhiteSpace(Model.MyName))
    {
        <p>welcome, your name is @Model.MyName</p>
    }
}

Since you have the @using, the Razor code inside it does not need the @. But, if you have an HTML element, then you will need to use the @, like on the Welcome text.

like image 136
Denis V Avatar answered Nov 13 '22 19:11

Denis V


There's no need to add @ sign in front of "if". The code should be like this:

@model WebApplication9.Models.Names


 @using (Html.BeginForm())
 {
      Html.TextBoxFor(m => m.Name)

      <button type="submit">Submit</button>

     if (!string.IsNullOrWhiteSpace(Model.MyName))
{
    <p>welcome, your name is @Model.MyName</p>
}

}

like image 22
Auguste Avatar answered Nov 13 '22 17:11

Auguste