无法访问已发布的表单数据(MVC)

时间:2013-02-04 11:20:02

标签: c# asp.net-mvc

如何在操作方法中访问已发布的表单数据并在视图中显示

我正在MVC中创建一个输入向导。有两个视图,一个用于从用户获取输入,另一个用于显示输入数据。

以下是模型的代码:

 public class Info
  {
    public int CustomerId { set; get; }
    public double Price { set; get; }
    public string name { set; get; }
  }
}

控制器代码 -

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

    public ActionResult DisplayCustomer(FormCollection frm)
    {
        Info info = new Info();

        info.name = Convert.ToString( Request.Form["name"]);
        info.Price = Convert.ToDouble(Request.Form["price"]);
        info.CustomerId = Convert.ToInt32(Request.Form["customerid"]);

        return View(info);
    }

FillCustomer View的代码 -

<form method="post" action="DisplayCustomer">
Name: <input type="text" id="name" /><br />
Price: <input type="text" id="price" /><br />
CustomerId: <input type="text" id="customerid" />
<br />
<input type="submit" id="btn1" />
</form>
</body>
</html>

DisplayCustomer View代码 -

<body>
<div>
Name is <%=Model.name %> and ID is <%=Model.CustomerId %>

<%if (Model.Price > 200)
  {%>

Greater than 200

<%}
  else %>

<%{%>Lesser than 200 

    <%} %>
    </div>
</body>
</html>

我使用调试器检查,控制器没有获取发布的数据。

3 个答案:

答案 0 :(得分:3)

表单的输入元素应具有名称属性

<form method="post" action="DisplayCustomer">
Name: <input type="text" id="name" name="name" /><br />
Price: <input type="text" id="price" name="price" /><br />
CustomerId: <input type="text" id="customerid" name="customerid" />
<br />
<input type="submit" id="btn1" />
</form>

现在您将获得表单数据

        Info info = new Info();
        info.name = Convert.ToString( Request.Form["name"]);
        info.Price = Convert.ToDouble(Request.Form["price"]);
        info.CustomerId = Convert.ToInt32(Request.Form["customerid"]);

在控制器中,表单数据作为键/值对接收。密钥是从名称属性中生成的。

答案 1 :(得分:1)

您正在使用MVC,因此DisplayCustomer方法中的参数是从视图传递的模型,该模型由模型绑定器隐式创建。将类型从FormCollection更改为Info类,如下所示:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DisplayCustomer(Info model)
{
   // you can now access to Info properties
}

这样就可以填充Info对象的值,我认为这就是你想要完成的事情。

答案 2 :(得分:0)

我认为您错过了编写DisplayCustomer函数的属性顶部。写它,我希望它会工作。

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DisplayCustomer(FormCollection frm)
{
    Info info = new Info();

    info.name = Convert.ToString( Request.Form["name"]);
    info.Price = Convert.ToDouble(Request.Form["price"]);
    info.CustomerId = Convert.ToInt32(Request.Form["customerid"]);

    return View(info);
}