ASP.NET MVC表单帖子

时间:2010-10-08 15:54:42

标签: asp.net-mvc forms post

我是ASP.NET MVC应用程序的初学者。我要做的是创建一个带有一些输入的表单,用户将填写这些表单,一旦用户单击post按钮,我希望发布表单并填写信息并准备打印。我现在正在做的方式如下:

// the controller that returns the initial form using ReportCreate.aspx which creates a Html form
public ActionResult ReportCreate()
{
    return View(viewData);
}


// my post action which gets the information for the submitted form
// and use the ReportPost.aspx to view a similar page as ReportCreate.aspx but with all the Html.TexBox inputs replaced with their values obtained from the submitted form      
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ReportCreate(FormCollection form)
{
    ReportFormData formData = new ReportFormData();

    formData.Date = form["date"];
    formData.Company = form["company"];
    formData.SiteNameA = form["siteNameA"];
    formData.SiteNameB = form["siteNameB"];
    formData.FreqBand = form["freqBand"];
    formData.FileNumber = form["fileNumber"];
    formData.ResponseDate = form["responseDate"];

    formData.SiteAddressA = form["siteAddressA"];
    formData.SiteAddressB = form["siteAddressB"];

    this.TempData.Add("viewData", viewData);

    return View("ReportPost", formData);
}

我不喜欢这种方式,我需要保持相似的aspx页面(ReportCreate.aspx和ReportPost.aspx),如果我需要对它们进行任何更改,我需要将它们一起修改表格的外观。我觉得应该有一种更专业的方式来处理这个常见问题。我试图在网上查找,但无法得到任何东西。请告诉我。非常感谢提前。

2 个答案:

答案 0 :(得分:2)

如果要以相同的形式显示发布的数据,只需使用与创建数据时相同的aspx页面。

但通常的方法是有一页:

  • 创建 - 首次输入值并在成功输入重定向到
  • 之后输入
  • 详细信息 - 数据不在表单上但作为常规文本

如果需要修改数据,请使用

  • 修改

显示数据集合

  • 索引

需要注意的另一点是,您不需要手动将表单中的所有值设置为ReportFormData类,而是:

[HttpPost]
public ActionResult Create(ReportFormData formData) 
{
  if(!ModelState.Isvalid){
     return View(formData);
  }
  else
  {
   RedirectToAction("Index");
  } 
}

答案 1 :(得分:0)

如果除了文本框之外的所有格式都是标签,那么只需在视图中使用条件来确定是否应该显示文本框。

<%if(model.ReadOnly){%><%=Html.LabelFor(m => m.Company)%><%else%><%=Html.TextBoxFor(m => m.Company)%><%}%>