我很难将文本框中的数据导入Controller。我在Sanderson的书“Pro ASP.NET MVC框架”中已经阅读了几种方法来实现这一点,但是没有取得任何成功。
另外,我在网上遇到过几个类似的问题,但也没有取得任何成功。好像我错过了一些相当基本的东西。
目前,我正在尝试使用action方法参数方法。有人可以指出我出错的地方或提供一个简单的例子吗?提前谢谢!
使用Visual Studio 2008,ASP.NET MVC2和C#: 我想做的是获取在“调查员”文本框中输入的数据,并使用它来过滤控制器中的调查员。我计划在List方法(已经正常工作)中执行此操作,但是,我正在使用SearchResults方法进行调试。
这是我视图中的文本框代码,SearchDetails:
<h2>Search Details</h2>
<% using (Html.BeginForm()) { %>
<fieldset>
<%= Html.ValidationSummary() %>
<h4>Investigator</h4>
<p>
<%=Html.TextBox("Investigator")%>
<%= Html.ActionLink("Search", "SearchResults")%>
</p>
</fieldset>
<% } %>
以下是我的控制器InvestigatorsController的代码:
private IInvestigatorsRepository investigatorsRepository;
public InvestigatorsController(IInvestigatorsRepository investigatorsRepository)
{
//IoC:
this.investigatorsRepository = investigatorsRepository;
}
public ActionResult List()
{
return View(investigatorsRepository.Investigators.ToList());
}
public ActionResult SearchDetails()
{
return View();
}
public ActionResult SearchResults(SearchCriteria search)
{
string test = search.Investigator;
return View();
}
我有一个调查员课程:
[Table(Name = "INVESTIGATOR")]
public class Investigator
{
[Column(IsPrimaryKey = true, IsDbGenerated = false, AutoSync=AutoSync.OnInsert)]
public string INVESTID { get; set; }
[Column] public string INVEST_FNAME { get; set; }
[Column] public string INVEST_MNAME { get; set; }
[Column] public string INVEST_LNAME { get; set; }
}
并创建了一个SearchCriteria类,看看我是否可以让MVC将搜索条件数据推送到它并在控制器中抓取它:
public class SearchCriteria
{
public string Investigator { get; set; }
}
}
我不确定项目布局是否与此有关,但我正在使用Sanderson建议的3项目方法:DomainModel,Tests和WebUI。 Investigator和SearcCriteria类位于DomainModel项目中,此处提到的其他项目位于WebUI项目中。
再次感谢任何提示,技巧或简单示例!
麦克
答案 0 :(得分:1)
这应该为你做(无法验证这是完美的 - 从内存中输入):
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SearchDetails(FormCollection formValues)
{
var txtContents = formValues["Investigator"];
// do stuff with txtContents
return View();
}
答案 1 :(得分:1)
1。)您是否为View查看过ViewModels?从本质上讲,这就是您的SearchCriteria类。确保使用该模型强烈键入视图:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/MyMaster.Master" Inherits="System.Web.Mvc.ViewPage<SearchCritieria>"
还要确保使用HtmlHelper.TextBoxFor方法将此Investigator属性映射到SearchCritiera模型。在回发后,您的文本框值应该在那里:
'&lt;%= Html.TextBoxFor(model =&gt; model.Invesigator)%&gt;'
这里有一个关于使用ViewModel的很好的参考,我最近看了很多:
http://geekswithblogs.net/michelotti/archive/2009/10/25/asp.net-mvc-view-model-patterns.aspx
答案 2 :(得分:0)
尝试强烈输入页面以使用SearchCriteria自动提取数据,例如ex:
public partial class Search: ViewPage<SearchDetails>
答案 3 :(得分:0)
感谢大家的提示。出于学习目的,我需要返回并遵循强类型路线。如果我从一开始就这样做,我很想知道是否会遇到这个问题。
在那之前,以下工作:
将此代码用于表单:
<% using(Html.BeginForm(new { Action = "SearchResults"})) { %> <% } >
再次感谢您的帮助!
麦克