获取错误 - 字符后出现意外"if"关键字"@"。进入代码后,您不需要像 "if" 这样的结构前面加上前缀



im在视图中获取错误-"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元素,那么您将需要使用@,就像在Welcome文本中一样。

不需要在"如果";。代码应该是这样的:

@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>
     }
}

您必须删除if语句前面的@符号。

它应该是这样的:

@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>
    }
}

这里的代码不一致,您使用了两个不同的属性名称,即NameMyName。只使用一个。

您也没有在任何位置填充MyName属性?您正在对没有设置值的属性使用IsNullOrWhiteSpace。也试试这个:

public ActionResult test1()
{
     Names name = new Names();
     name.MyName = "Clown";
     return View(name);
}

您的Index操作方法有两个返回视图,删除一个。

请花时间学习一些ASP.NET MVC教程。学习需要一些时间,但从长远来看,这是最好的。

相关内容

最新更新