【问题标题】:Razor syntax to complete an MVC form用于完成 MVC 表单的 Razor 语法
【发布时间】:2017-10-12 13:13:39
【问题描述】:

我对在 C# 中使用 Razor 非常陌生,并且正在开展这个项目以试图更好地理解它。

这个应用程序应该在完成后要求用户输入三个整数,然后打印出这些整数的总和。现在,我已经设置了视图和控制器的基本框架。 (目前没有模型。)控制器设置为使用 HTTP-Post 协议,以便将信息发送到 HTML 表单。

我正在努力解决的是将数据直接传递给表单所需的代码,以及所需的任何参数,以便 ASP.net 将忽略两个同名控制器操作的存在(我m 告诉它应该能够在正确设置 Razor 语法后执行此操作)。

这里的任何指导都会非常有帮助。 (注意:我在完成的解决方案中要求使用 HTTP Post 协议。)

控制器:

public ActionResult Index(int firstInt = 0, int secondInt = 0, int thirdInt = 0)
    {
        return View();
    }

[HttpPost]
public ActionResult Index(int firstInt = 0, int secondInt = 0, int thirdInt = 0)
    {
        int sum = firstInt + secondInt + thirdInt;
        ViewBag.result = sum;
    }

索引视图:

<form action="" method="post">
<table>
<tr><td>Enter the 1st Number: <input id="firstInt" name="firstInt" type="text" value="0" /></td></tr>
<tr><td>Enter the 2nd Number: <input id="secondInt" name="secondInt" type="text" value="0" /></td></tr>
<tr><td>Enter the 3rd Number: <input id="thirdInt" name="thirdInt" type="text" value="0" /></td></tr>
<tr>
<td><input id="Submit" type="submit" value="submit" /><input id="Reset" type="reset" value="reset" /></td>
</tr>
<tr>
<td>Sum =  @ViewBag.result</td>
</tr>
</table>
</form>

【问题讨论】:

    标签: c# asp.net asp.net-mvc razor http-post


    【解决方案1】:

    您需要确保您的同名方法具有唯一的签名。由于您提到用户通过表单输入数字,因此没有理由在 GET 操作方法中包含这些参数。只需删除它,它现在应该可以工作了。

    public ActionResult Index()
    {
        return View();
    }
    

    您还需要在 HttpPost 操作中使用 return View(); 语句。否则会出现编译错误。

    [HttpPost]
    public ActionResult Index(int firstInt = 0, int secondInt = 0, int thirdInt = 0)
    {
        int sum = firstInt + secondInt + thirdInt;
        ViewBag.result = sum;
        return View();
    }
    

    如果您将有许多来自表单的参数值,我建议创建一个具有这些属性的视图模型并将其用作参数。

    【讨论】:

    • 另外,您需要在 Post 方法中 return View();。
    【解决方案2】:

    通常您对 Razor 视图所做的是声明模型,并使用 Razor 方法输出表单和表单元素。正如 Shyju 所说,您需要对动作进行独特的签名。

    @using MyModelNamespace
    @model MyModel
    
    @using (Html.BeginForm("Index", "HomeController", routevalues, etc..) {
         Html.TextBoxFor(m => m.firstInt);
    }
    

    您的帖子操作应将模型作为参数

    public ActionResult Index() {
         return View();
    }
    
    [HttpPost]
    public ActionResult Index(MyModel m) {
        int sum = m.firstInt + m.secondInt + m.thirdInt;
        ViewBag.result = sum;
        return View(m);
    }
    

    您可以在操作中设置 ViewBag 状态。

    【讨论】:

    • 我之前尝试过类似的方法,在视图中声明模型。我总是遇到同样的错误,程序无法识别我的模型名称。
    • 您需要在视图顶部使用正确的@using 语句。编辑包括在内。
    • 我忘记在使用前加上@ 符号。还是您的意思是表单正在呈现但未路由到正确的提交操作?
    • 忽略我最后的两个 cmets。我能够让整个工作正常进行。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多