Link to home
Start Free TrialLog in
Avatar of homeshopper
homeshopperFlag for United Kingdom of Great Britain and Northern Ireland

asked on

NopCommerce search error:Input string was not in a correct format

I have the following code for an advanced search on products.
When a simple search is done it works, but when the checkbox for advanced is clicked
it gives the following error:
Input string was not in a correct format.
Thankyou in advance for any help given.
@model SearchModel
@{
    Layout = "~/Views/Shared/_ColumnsThree.cshtml";
    Html.AddTitleParts(T("PageTitle.Search").Text);
}
@using Nop.Core;
@using Nop.Core.Infrastructure;
@using Nop.Web;
@using Nop.Web.Models.Catalog;
@using Nop.Web.Extensions;
<script type="text/javascript">
    $(document).ready(function () {
        $("#@Html.FieldIdFor(model => model.As)").click(toggleAdvancedSearch);
        toggleAdvancedSearch();
    });
    function toggleAdvancedSearch() {
        if (getE('@Html.FieldIdFor(model => model.As)').checked) {
            $('#pnl-advanced-search').show();
            $('#pnl-advanced-search2').hide();
        }
        else {
            $('#pnl-advanced-search').hide();
            $('#pnl-advanced-search2').show();
        }
    }
</script>
<div class="search-panel">
@using (Html.BeginRouteForm("ProductSearch", FormMethod.Get))
{
    <div class="search-input">
        <table class="basic-search">
            <tbody>
                <tr>
                    <td style="border:0px solid yellow; width:100px;">
                        @Html.LabelFor(model => model.Q):
                    </td>
                    <td style="border:0px solid blue;">
                        @Html.TextBoxFor(model => model.Q, new { @class = "searchtext" })
                    </td>
                    <!-- :IAN:S-but: -->
                    <td style="border:0px solid red;width:50px;">
                        <input type="submit" id="btnsearch" name="btnsearch" class="Button3" value="@T("Search")" />
                    </td>
                    <!-- :IAN:S-Adv: -->
                    <td style="border:0px solid green;width:120px;">
                        &nbsp;&nbsp;
                        @Html.CheckBoxFor(model => model.As)
                        @Html.LabelFor(model => model.As)
                    </td>
                </tr>
               
                <tr>
                    <td colspan="2">
                        <table class="adv-search" id="pnl-advanced-search">
                            <tbody>
                                @if (Model.AvailableCategories.Count > 0)
                                {
                                    <tr>
                                        <td class="title">
                                            @Html.LabelFor(model => model.Cid):
                                        </td>
                                        <td class="data">
                                            @Html.DropDownListFor(model => model.Cid, Model.AvailableCategories)
                                        </td>
                                    </tr>
                                }
                                @if (Model.AvailableManufacturers.Count > 0)
                                {
                                    <tr>
                                        <td class="title">
                                            @Html.LabelFor(model => model.Mid):
                                        </td>
                                        <td class="data">
                                            @Html.DropDownListFor(model => model.Mid, Model.AvailableManufacturers)
                                        </td>
                                    </tr>
                                }
                                <tr>
                                    <td class="title">
                                        @T("Search.PriceRange"):
                                    </td>
                                    <td class="data">
                                        @T("Search.PriceRange.From")
                                        @Html.TextBoxFor(model => model.Pf, new { style = "width: 100px" })
                                        @T("Search.PriceRange.To")
                                        @Html.TextBoxFor(model => model.Pt, new { style = "width: 100px" })
                                    </td>
                                </tr>
                                <tr>
                                    <td class="data" colspan="2">
                                        @Html.CheckBoxFor(model => model.Sid)
                                        @Html.LabelFor(model => model.Sid)
                                    </td>
                                </tr>
                            </tbody>
                        </table>
            @*<div id="pnl-advanced-search2">*@                              
            @*{ViewContext.Writer.Write("<br/>");}
            @{ViewContext.Writer.Write("<br/>");}*@
            @*</div>*@  
                    </td>
                </tr>
                <tr>
                @if (!String.IsNullOrEmpty(Model.Warning))
                {
                        <td colspan="2">
                            <span class="warning">
                                @Model.Warning
                            </span>
                        </td>
                }
                </tr>
            </tbody>
        </table>
    </div> 
    <div class="search-results">
        @if (Model.NoResults)
        {
            <div style="padding-left:13px;padding-top:25px;">
            <span class="result">
                <b>NO SEARCH RESULTS FOUND</b>
                <p>We're sorry, no products were found for your search: <span style=" color:Maroon;"><b>@Model.Q</b></span></p>
                <b>TRY YOUR SEACH AGAIN USING THESE TIPS:</b>
                <p>
                    <ul>
                        <li>Double check the spelling. Try varying the spelling</li>
                        <li>Limit the search to one or two words</li>
                        <li>Try a new search</li>
                    </ul>
                </p>
                <p><b>Alternatively click on one of our product groups:<br />
                <span style=" color:Maroon;">or call us on 01844 220 500</span></b></p>
                <div style="padding-left:50px;">
                @foreach (var category in Model.AvailableCategories.Where(c => !c.Text.Contains(">>") && c.Text != "All"))
                {
                    <a href="@Url.RouteUrl("Category", new { categoryId = category.Value, SeName = category.Text.Replace("&", "-").Replace(",", "-").Replace(":", "-").Replace(" ", "-").Replace("/", "-") })">@category.Text</a>
                    <br />             
                }
                </div>
            </span>
            </div>
        }
        else
        {     
            <!-- product-list -->              
            <div class="">        
					@*foreach (var product in Model.Products.Where(p => p.Name.ToLower().Contains(Model.Q.ToLower())))*@
                    @foreach (var product in Model.Products.Where(p => p.AdminComment.ToLower().Contains(Model.Q.ToLower())))
                    {   
                       @Html.Partial("_SearchResultProductBox", product)        
                    }
            @{ViewContext.Writer.Write("<table style='position: relative; top:0px; width:699px; height:auto; left:-15px; background-color: White; border:0px solid silver; color: Blue;'>");}
            @{ViewContext.Writer.Write("<tr>");}
            @{ViewContext.Writer.Write("<td>");}
            Your search term <span style=" color:Maroon;"><b>@Model.Q</b></span> appears in several of our categories.<br />
            Alternatively click on one of our product groups below:<br />
            <span style=" color:Maroon;"><b>or call us on 01844 220 500</b></span>
            @{ViewContext.Writer.Write("</td>");}
            @{ViewContext.Writer.Write("</tr>");}
            @{ViewContext.Writer.Write("<tr>");}
            @{
              int nCount = 0;
              foreach (var category in Model.AvailableCategories)
              {
                  if (nCount == 2)
                  {
                      nCount = 0;
                      ViewContext.Writer.Write("</tr>");
                      ViewContext.Writer.Write("<tr>");
                  }
                  ViewContext.Writer.Write("<td>");
                    <a href="@Url.RouteUrl("Category", new { categoryId = category.Value, SeName = category.Text.Replace(":", "-").Replace(" ", "-").Replace("/", "-") })">@category.Text</a>
                  ViewContext.Writer.Write("</td>");
                  nCount = nCount + 1;
              }
            }
            @{ViewContext.Writer.Write("</tr>");}
            @{ViewContext.Writer.Write("</table>");}	
            </div>        
            <div class="clear">
            </div>
            <div class="pager" style="padding-top:10px;">
                @Html.Pager(Model.PagingFilteringContext).QueryParam("pagenumber").BooleanParameterName("as").BooleanParameterName("sid")
            </div>         
        }
    </div>
}
</div>

Open in new window

Avatar of Ioannis Paraskevopoulos
Ioannis Paraskevopoulos
Flag of Greece image

On which line do you get this error?
Avatar of homeshopper

ASKER

It does not indicate any line for the error, below is the stack trace:
Thanks in advance.
[FormatException: Input string was not in a correct format.]
   System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) +10896279
   System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) +145
   System.String.System.IConvertible.ToInt32(IFormatProvider provider) +46
   System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) +510
   System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType, Boolean& coercedToDataFeed, Boolean& typeChanged, Boolean allowStreaming) +5344343

[FormatException: Failed to convert parameter value from a String to a Int32.]
   System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType, Boolean& coercedToDataFeed, Boolean& typeChanged, Boolean allowStreaming) +5343335
   System.Data.SqlClient.SqlParameter.GetCoercedValue() +185
   System.Data.SqlClient.SqlParameter.Validate(Int32 index, Boolean isCommandProc) +102
   System.Data.SqlClient.SqlCommand.SetUpRPCParameters(_SqlRPC rpc, Int32 startCount, Boolean inSchema, SqlParameterCollection parameters) +122
   System.Data.SqlClient.SqlCommand.BuildRPC(Boolean inSchema, SqlParameterCollection parameters, _SqlRPC& rpc) +78
   System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) +1406
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +177
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +134
   System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
   System.Data.Common.DbCommand.ExecuteReader() +12
   Nop.Data.NopObjectContext.ExecuteStoredProcedureList(String commandText, Object[] parameters) +556
   Nop.Services.Catalog.ProductService.CustomSearchProducts(Int32 categoryId, Int32 manufacturerId, Nullable`1 featuredProducts, Nullable`1 priceMin, Nullable`1 priceMax, Int32 productTagId, String keywords, Boolean searchDescriptions, Int32 languageId, IList`1 filteredSpecs, ProductSortingEnum orderBy, Int32 pageIndex, Int32 pageSize, Boolean showHidden) +3686
   Nop.Web.Controllers.CatalogController.Search(SearchModel model, SearchPagingFilteringModel command) +1580
   lambda_method(Closure , ControllerBase , Object[] ) +147
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +214
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +253
   System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +21
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +253
   System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +21
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +253
   System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +21
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +253
   System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +21
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +253
   System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +21
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +324
   System.Web.Mvc.Controller.ExecuteCore() +106
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +91
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +34
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +19
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +48
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9514928
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Open in new window

Your problem is this:

[FormatException: Failed to convert parameter value from a String to a Int32.]

But you would better add a breakpoint to your view and see where this occurs.

If you still need help, then post your findings.
The error is occuring somewhere in one of the following server side methods:
Nop.Data.NopObjectContext.ExecuteStoredProcedureList(String commandText, Object[] parameters)
Nop.Services.Catalog.ProductService.CustomSearchProducts(Int32 categoryId, Int32 manufacturerId, Nullable`1 featuredProducts, Nullable`1 priceMin, Nullable`1 priceMax, Int32 productTagId, String keywords, Boolean searchDescriptions, Int32 languageId, IList`1 filteredSpecs, ProductSortingEnum orderBy, Int32 pageIndex, Int32 pageSize, Boolean showHidden)
Nop.Web.Controllers.CatalogController.Search(SearchModel model, SearchPagingFilteringModel command)
My guess is that one of the string parameters in ProductService.CustomSearchProduct() method is being converted to a int when it is passed as a parameter into a stored procedure.  The JavaScript code may be passing in a "" or " " instead of a null.  The only way to be sure would be to set a break point and debug the code at this level as jyparask suggested.
Thankyou.
Breakpoints does not stop the process running.
<input type="submit" id="btnsearch" name="btnsearch" class="Button3" value="@T("Search")" /> line 42
@Html.CheckBoxFor(model => model.As) line 47
@Html.LabelFor(model => model.As) line 48
When inputing text at line 42 with checkbox line 47 unchecked gives search results.
When the checkbox is checked, it gives the error.
If numbers only are inputed, no error is given and no search results.
Thanks in advance.
Sorry, just posted and did not see suggestions
In order to solve the problem you need to determine how the SearchModel model is converted into the parameters of the ProductService.CustomSearchProducts() method.  It looks like the model.AS property is be incorrectly mapped to an integer parameter or some other logic is incorrect.

Do you have access to the server side source code?  You need to debug the ProductService.CustomSearchProducts() method or the CatalogController.Search() to determine how the model.AS property is being used.
I have just taken on a legacy project and only the customised view code is available.
The customised code for model & controller was compiled into a ddl.
I have been able download full source code for version 2.65,
but do not know what customisations where made.
What I'll do is first get the view code to work with the other full source etc.
It might take quite a while.
Then I'll be able to try your suggestions.
Thanks in advance for the help given
ASKER CERTIFIED SOLUTION
Avatar of MogalManic
MogalManic
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thankyou for all your help.
Later tonight I'll take a look at your suggestions.
One again, Thanks.
HI MogalManic,
Sorry it has been a while to get back to this post.
I did download the source code for version 2.65
There must have been many alterations made by the previous developer.
However, I have now been able to get the advanced search finished.
Thanks, your last suggestions where very helpfull.
I'll award the points now.