木子屋 Dnawo's BLOG

ASP.NET MVC3同一View多个表单测试

👤 dnawo 📅 2012-08-15 👁 5296 👍 0 💬 0 🔄 来源:本站原创
测试1:同一View单个表单测试

View:
<h2>@ViewBag.Message</h2>
<p>
    @using (Html.BeginForm()) { 
    <input type="text" name="f1" />
    <input type="submit" value="submit" />
    }
</p>

Action:
[HttpPost]
public ActionResult Index(string f1)
{
    ViewBag.Message = string.Format("f1={0}", f1);

    return View();
}

结果正常:

图片

测试2:View表单和Action参数名称不一致测试

Action:
[HttpPost]
public ActionResult Index(string f2)
{
    ViewBag.Message = string.Format("f1={0}", f2);

    return View();
}

运行结果:

图片

可见,View表单名称必须和Action参数名称对应,Action中才能正确取值。

测试3:同一View两个表单测试

View:
<h2>@ViewBag.Message</h2>
<p>
    @using (Html.BeginForm()) { 
    <input type="text" name="f1" />
    <input type="submit" value="submit" />
    }
    @using (Html.BeginForm())
    { 
    <input type="text" name="f2" />
    <input type="text" name="f3" />
    <input type="submit" value="submit" />
    }
</p>

Action:
[HttpPost]
public ActionResult Index(string f1)
{
    ViewBag.Message = string.Format("f1={0}", f1);

    return View();
}

[HttpPost]
public ActionResult Index(string f2, string f3)
{
    ViewBag.Message = string.Format("f2={0},f3={1}", f2, f3);

    return View();
}

项目生成通过,但在submit时出错:

图片

既然Action参数名和表单一一对应,为什么HttpPost时区分不出来呢?Action做如下修改后运行正常:
[HttpPost]
public ActionResult Index(string f1, string f2, int f3)
{
    ViewBag.Message = string.Format("f1={0},f2={1},f3={2}", f1, f2, f3);

    return View();
}

图片

评论(0)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 ASP.NET MVC3使用JsonResult返回Json数据… 下一篇 → Entity Framework Power Tools Bet…