I'm new in MVC, I want to perform Wildcard (*, !) search on database. This is what I have done by using Regex:
Controller:
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
CrossWord_dbEntities db = new CrossWord_dbEntities();
public ActionResult Index(string searching)
{
var regEx = WildcardToRegex(searching);
return View(db.tbl_values.Where(x => Regex.IsMatch(x.Name, regEx, RegexOptions.Singleline)));//.ToList()));
}
public static string WildcardToRegex(string pattern)
{
return "^" + Regex.Escape(pattern).
Replace("\\*", ".*").
Replace("\\?", ".") + "$";
}
}
}
View:
@model IEnumerable<WebApplication1.Models.tbl_values>
<br /><br />
@using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
@Html.TextBox("searching") <input type="submit" value="Search" />
}
<table class="table table-striped">
<thead>
<tr>
<th>Results</th>
</tr>
</thead>
<tbody>
@if (Model.Count() == 0)
{
<tr>
<td colspan="3" style="color:red">
No Result
</td>
</tr>
}
else
{
foreach (var item in Model)
{
<tr>
<td>
@item.Name
</td>
</tr>
}
}
</tbody>
</table>
With the above code when i run i get an exception in line: "@if (Model.Count() == 0)"
LINQ to Entities does not recognize the method 'Boolean IsMatch(System.String, System.String, System.Text.RegularExpressions.RegexOptions)' method, and this method cannot be translated into a store expression.
what i have to do to fix this problem?
i tried to write in the return line of the controller adding "ToList()"
return View(db.tbl_values.Where(x => Regex.IsMatch(x.Name, regEx, RegexOptions.Singleline).ToList()));
but i get the same expction on this line.
thanks Amir