我有一个接收一个参数的动作方法:
public ActionResult Citizens(string docId){
//bla bla
}
在视图中我有以下内容:
@using(Html.BeginForm("Citizens","DocSearch",FormMethod.Get)){
@Html.TextBox("docId",null,new {id="txtSearch"})
<input type="submit" value="Search" />
}
请注意,表单方法是GET而不是POST
我的RouteConfig类中有以下Url映射规则:
routes.MapRoute(name: "DocUrl",
url: "{controller}/{action}/{docid}");
当我点击提交按钮时,我希望docId是txtSearch的值。但它不是,而是使用该值替换路径中的docid,而是将具有文本框值的查询字符串添加到url中。我该怎么办才能让它发挥作用?
编辑:为了提供更多见解,让我告诉你我在我的行动方法中做了些什么。我检查了docId的值,如果它是&#34; 0&#34;然后我只返回视图而不传递任何模型。如果它与&#34; 0&#34;不同,我构建模型并将其传递给View动作。在剃须刀方面,我检查模型是否为空。如果它为null,那么我只提供一个搜索文本框和提交按钮,它(根据我想要的)转到相同的操作方法,但这次将docId参数设置为搜索文本框的值。这应该导致构建模型并将其发送回View,而View将相应地渲染模型。
@{if (Model == null)
{
<div class="google-search">
<div>
@using(Html.BeginForm("Citizens","DocSearch",FormMethod.Get)){
@Html.TextBox("docId",null,new {id="txtSearch"})
<input type="submit" value="Search" />
}
</div>
</div>
}
else
{Render the model}
public ActionResult Citizens(string docId)
{
if (docId != "0")
{
DocumentCitizenRepository docRepo = new DocumentCitizenRepository();
IEnumerable<DocumentCitizen> documents = docRepo.Documents.Where(x => x.DocID.Contains(docId)).ToList();
MiscellaneousRepository miscRepo = new MiscellaneousRepository();
IEnumerable<DocSearchViewModel> searchResults = (from doc in documents
join officer in miscRepo.Officers
on doc.AddressedOfficerID.Value equals officer.OfficerID
select new DocSearchViewModel
{
AddressedTo = string.Format("{0} {1} {2}", officer.LastName, officer.FirstName, officer.Patronymic),
Author = string.Format("{0} {1} {2}", doc.LastName, doc.FirstName, doc.Patronymic),
DocDate = doc.ReceivedDate,
DocNumber = doc.DocID,
Content = doc.TextValues.Subject
}).ToList();
return View(viewName: "Index", model: searchResults);
}
else//We'll check if the model is null on the razor and act accordingly.
{
return View(viewName: "Index");
}
}
这是我提交后获得的HTML:
<form action="/DocSearch/Citizens/0" method="get" novalidate="novalidate">
<input type="text" name="docId" ,id="txtDocNumber">
<input type="submit" value="Search">
</form>
答案 0 :(得分:2)
在路线中选择docId
routes.MapRoute(name: "DocUrl",
url: "{controller}/{action}/{docid}",
defaults: new {controller = " DocSearch",
action = "Citizens",
docid = UrlParameter.Optional}
);
<强>解释强>
Html.BeginForm实现使用UrlHelper.GenerateUrl
根据您的路由集合生成Url。基本上它与您使用@Url.RouteUrl("DocUrl")