razor asks for ; when doing using(Html.BeginForm()

2019-02-22 05:22发布

问题:

@using(Html.BeginForm()){
Name:
    @Html.TextBoxFor(o => o.Name)
        <input type="submit" value="submit" />
    }

this gives error CS1002: ; expected

it works if I remove the Name:

or if I do it like this:

<form action="@Url.Action("AddHuman")" method="post">
Name:
    @Html.TextBoxFor(o => o.Name)
        <input type="submit" value="submit" />
</form>

回答1:

The problem is most likely with your Name: literal. Since you are inside a code block, Razor assumes that the next lines are code lines. You can escape this with either prepending Name: with @: or by wrapping it with <text></text>. The text tag is special for Razor and will be removed when it is parsed by the view engine.

The reason your <input> will be fine is that Razor recognizes that it is a markup tag and will write it out to the response stream, with Name: it can't assume that since it isn't an actual markup tag.



回答2:

Sometimes razor gets confused, so you will need to wrap your code inside of a html tag. In case you do not wish to add additional html tags just because razor doesn't gets it, you can use <text> which will be removed.

@using(Html.BeginForm()){
   <text>
       Name:
       @Html.TextBoxFor(o => o.Name)
       <input type="submit" value="submit" />
   </text>
}