Reputation: 403
I am having some issue with below code. I have 2 fields and one search button. when I give value only for the field Holiday
and search, it doesn't hit the controller. But if I give value for the field Year
, then only it does hit the controller and passes value of both the field to it.
Index.cshtml:
@using (Ajax.BeginForm("Search", "Holiday", new System.Web.Mvc.Ajax.AjaxOptions
{
InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "holidaylist"
}))
{
<table>
<tr>
<td>Holiday: </td>
<td><input id="searchtext" name="searchtext" type="text" /></td>
<td>Year: </td>
<td><input id="year" name="year" type="text" /> </td>
<td><input type="submit" value="View" id="BtnSubmit" /></td>
</tr>
</table>
}
Controller:
HttpPost]
public ActionResult Search(string searchtext, int year)
{
try
{
string selyear = year.ToString();
Upvotes: 1
Views: 839
Reputation: 6130
This route is always expecting a year, because year is not an optional parameter. You can solve this by making year nullable:
[HttpPost]
public ActionResult Search(string searchtext, int? year)
{
try
{
if (year != null) //you will need to handle the case where year = null
{
string selyear = year.ToString();
Upvotes: 2