wholee1
wholee1

Reputation: 1501

MVC3 SqlFunctions.StringConvert Method

I am trying to convert decimal value to string.

My coding is this:

public ActionResult Search(string searchString)
    {
    product = product.Where(a => a.model.ToUpper().Contains(searchString.ToUpper())
                               || a.Category.name.ToUpper().Contains(searchString.ToUpper()) 
                               || SqlFunctions.StringConvert((decimal)a.displaySize).Contains(searchString));
    return View(product.ToList());
    }

When searchString value is '5' instead of decimal value, it will be shown product list. However, if searchString value is '5.5', it won't display the product list.

I don't know why really..

Could you help me?

Many thanks.

Upvotes: 1

Views: 549

Answers (2)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93434

You don't need the ToUpper's if you're using a case-insensitive colation in SQL Server (which is the default). I doubt Contains is what you actually want, you probably want something like this:

public ActionResult Search(string searchString) 
{
    decimal d = 0;
    bool isDecimal = decimal.TryParse(searchString, out d);
    product = product.Where(a => a.model.Contains(searchString) 
                           || a.Category.name.Contains(searchString)  
                           || (isDecimal && a.displaySize == d) ); 
    return View(product.ToList()); 
} 

Also, consider what happens when a model or category contains a number, your search will return a result.. maybe that's ok. Just pointing it out.

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

It would probably be easier to convert searchString to a decimal, try this:

public ActionResult Search(string searchString)
{
    var searchVal = decimal.Parse(searchString);

    product = product.Where(a => a.model.ToUpper().Contains(searchString.ToUpper())
                           || a.Category.name.ToUpper().Contains(searchString.ToUpper()) 
                           || a.displaySize == searchVal);
    return View(product.ToList());
}

You may want to use TryParse instead to ensure typesafety, depending on where searchString is coming from

Upvotes: 1

Related Questions