MVC - 从控制器返回数据的视图

时间:2012-11-30 19:58:46

标签: asp.net-mvc asp.net-mvc-3

我的问题:如果我们已经创建了一个强类型的视图,那么为什么我们需要将模型对象从控制器post方法返回到视图 - MVC 4 asp.net?

例如:我有计算器视图:

@using (Html.BeginForm())
{
    <p>Number One : @Html.TextBoxFor(m => m.numberOne)</p>
    <p>Number Two : @Html.TextBoxFor(m => m.numberTwo)</p>
        <input type="submit" value ="Addition" name="calculateOperation"  />
           <input type="submit" value ="Subtraction" name="calculateOperation" />
           <input type="submit" value ="Multiplication" name="calculateOperation" />
           <input type="submit" value ="Division" name="calculateOperation" />
}

@using (Html.BeginForm())
{
         <p>Output     : @Html.TextBoxFor(m => m.result)</p>

}

和控制器:

public ActionResult Calculate(Calculator model, string calculateOperation)
{


    if (calculateOperation.Equals("Addition"))
    {
        int[] array = { 1, 12, 5, 26, 7, 14, 3, 7, 2 };
        model.result = model.numberOne + model.numberTwo;
    }
    if (calculateOperation.Equals("Subtraction"))
    {
        model.result = model.numberOne - model.numberTwo;
    }
    if (calculateOperation.Equals("Multiplication"))
    {
        model.result = model.numberOne * model.numberTwo;
    }
    if (calculateOperation.Equals("Division"))
    {
        model.result = model.numberOne / model.numberTwo;
    }


    return View(model);

}

如果我没有返回模型对象,我就没有得到model.result的值。

寻找合理的理由。

4 个答案:

答案 0 :(得分:1)

好吧,你不必发回模型,你可以只使用FormCollection参数,但是你必须获取值并将它们转换为你自己的正确类型。

public ActionResult Calculate(FormCollection form, string calculateOperation)
{
    // Need to check if form["numberOne"] is null or empty or do a int.TryParse()
    int numberOne = int.Parse(form["numberOne"]);
}

使用强类型模型,您可以通过asp.net mvc中的model binders免费获得该模型。代码看起来更干净,更容易使用。

使用模型,您还可以获得属性的强大功能,例如validation和脚手架。使用具有验证属性的模型验证大多数场景会更清晰,更容易。


在这种情况下,您需要将模型发送到视图,因为视图需要它。这就是它的设计方式。如果你不将它存储在某个地方,模型或视图如何知道你已经进行了计算?当然你也可以使用ViewBag:

ViewBag["result"] = model.numberOne + model.numberTwo;

在你看来:

<p>Output     :@Html.TextBox("result", (string)ViewBag["result"])</p>

答案 1 :(得分:1)

HTTP是无状态协议。因此,当您在服务器上工作时,如果您希望它在客户端上显示某些内容,则必须将其发回。 MVC强类型视图实际上只是渲染引擎之上的抽象。

当您“提交”表单时,您正在执行HTTP POST回到您的控制器操作(http请求)。

致电

 return View(model) 

表示您正在发送HTTP响应,该响应返回呈现的html页面(使用您的视图)。在您的情况下,您只是将模型作为参数传递。

答案 2 :(得分:0)

我总是认为这是为了涵盖存在某种解释或响应类型数据的情况。

例如。您提交要添加到数据库的地址,并且您有一个检查地址是否正确的服务。如果它是正确的,它会被持久化,否则会被纠正,添加到原始对象的特殊字段中并发送回来进行确认。

答案 3 :(得分:0)

没有实际要求您的控制器方法返回消耗该模型或任何其他模型的任何内容。因此,您仍然需要明确查看要返回的View和与之关联的数据。

他们可以为View添加某种重载,隐含地假设它应该在方法参数中使用一些ViewModel,但这是非直观且不必要的。