Solved

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

Posted on 2014-07-24
11
733 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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
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
 

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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

831 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