Solved

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

Posted on 2014-07-24
11
719 Views
Last Modified: 2014-07-30
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

0
Comment
Question by:homeshopper
  • 6
  • 3
  • 2
11 Comments
 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
ID: 40218598
On which line do you get this error?
0
 

Author Comment

by:homeshopper
ID: 40219186
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

0
 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
ID: 40219260
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.
0
 
LVL 21

Expert Comment

by:MogalManic
ID: 40219454
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.
0
 

Author Comment

by:homeshopper
ID: 40219467
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.
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

Author Comment

by:homeshopper
ID: 40219469
Sorry, just posted and did not see suggestions
0
 
LVL 21

Expert Comment

by:MogalManic
ID: 40219485
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.
0
 

Author Comment

by:homeshopper
ID: 40219509
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
0
 
LVL 21

Accepted Solution

by:
MogalManic earned 500 total points
ID: 40219812
On a whim I googled the namespace and found that nopCommerce is an open source product.  You can download the source code for your version (2.65) here (http://nopcommerce.codeplex.com/releases/view/90459).  The product site is located at http://www.nopcommerce.com/.  There is an ebook you can purchase for $19.95

Assuming that your version is not customized, the code "should" be the same.  I found the CatelogController.Search method and the model.as processing looks like this:
if (model.As)
{
	//advanced search
	var categoryId = model.Cid;
	if (categoryId > 0)
	{
		categoryIds.Add(categoryId);
		if (model.Isc)
		{
			//include subcategories
			categoryIds.AddRange(GetChildCategoryIds(categoryId));
		}
	}


	manufacturerId = model.Mid;

	//min price
	if (!string.IsNullOrEmpty(model.Pf))
	{
		decimal minPrice = decimal.Zero;
		if (decimal.TryParse(model.Pf, out minPrice))
			minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(minPrice, _workContext.WorkingCurrency);
	}
	//max price
	if (!string.IsNullOrEmpty(model.Pt))
	{
		decimal maxPrice = decimal.Zero;
		if (decimal.TryParse(model.Pt, out maxPrice))
			maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(maxPrice, _workContext.WorkingCurrency);
	}

	searchInDescriptions = model.Sid;
}

Open in new window

I am not sure what values you are working with, but maybe the code above will help.
0
 

Author Comment

by:homeshopper
ID: 40219826
Thankyou for all your help.
Later tonight I'll take a look at your suggestions.
One again, Thanks.
0
 

Author Comment

by:homeshopper
ID: 40229366
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.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
creating a flowchart from an algorithm 5 22
Get String split 5 33
Hidden Field Value 10 34
Visual Studio 2013 debugging 2 19
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now