I'm running i开发者_Python百科nto an issue when posting a form back from different views... I'm using the same form and it will work in one view, but not the other. When it errors in the post, the parameter will pass as null. This is my form:
<% using (Html.BeginForm()) { %>
<table>
<tr>
<td colspan="4" style="line-height:20px;"><label for="Search.searchString">Search</label></td>
</tr>
<tr>
<td><%= Html.TextBox("Search.searchString") %>
</td>
<td><label for="Search.category"><nobr>In Category</nobr></label></td>
<td><%= Html.TextBox("Search.category") %></td>
<td><input type="submit" value="Search" /></td>
</tr>
</table>
<% } %>
I have 2 views... an Index and a Search view. When I post this form from the index view, it works fine. When I post it from the search view, it tells me that my Search object is null. This is my post method:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(Search search)
{
if (String.IsNullOrEmpty(search.searchString))
search.searchString = "all";
return RedirectToRoute("search", new RouteValueDictionary { { "search", search.searchString }, { "category", search.category } });
}
The post methods for both index and search are the same, so I'm rather confused as to why one works while the other doesn't. Any thoughts? Thanks for the help!
Does your second view inherit from your search object or does the model for the view inherit from the search object?
So your Index view <namespace.SearchObject>
and your Search <namespace.SearchObject>
Of if search inherits from <namespace.SearchView>
then your SearchView must inherit from SearchObject.
It's because your ActionResult method has the same name as the typed model your passing in.
Try using the ActionName attribute:
[ActionName("Search"), AcceptVerbs(HttpVerbs.Post)]
public ActionResult DoSearch(Search search)
{
return View();
}
Ok, I think I have this figured out.... I ended up modifying the html.beginform tag to the following...
using (Html.BeginForm("Index", "Home"))
and forced it to always use the index post method, and it works. Is this the best way to fix it though?
精彩评论