参见英文答案 Unexpected “foreach” keyword after “@” character2个 我在视图中得到错误 – “”test1.cshtml“ “@”字符后面的意外“if”关键字.一旦进入代码,你就不需要像“if”这样的结构加
我在视图中得到错误 – “”test1.cshtml“
“@”字符后面的意外“if”关键字.一旦进入代码,你就不需要像“if”这样的结构加前缀
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> } }
控制器代码
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(); }
型号代码
namespace WebApplication9.Models { public class Names { public string MyName { get; set; } } }尝试:
@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> } }
由于你有@using,里面的Razor代码不需要@.但是,如果你有一个HTML元素,那么你需要使用@,就像欢迎文本一样.