Skip to main content
 首页 » 编程设计

c#之如何在 asp.net MVC 3 上将传递的字符串参数转换为 int

2024年02月13日23freeliver54

我是 Asp.net MVC Develpoer,我在将字符串转换为 int 时遇到问题,因为我
因为我在搜索时需要它。当我尝试在 Controller 上编写这段代码时:

public ViewResult Search(string textboxmvc) 
{ 
    var student = from i in db.StudentSet  select i; 
 
    if (!String.IsNullOrEmpty(textboxmvc)) 
    { 
        student = student.Where(s => s.FirstName.ToUpper().Contains(textboxmvc.ToUpper()) 
                                   || s.LastName.ToUpper().Contains(textboxmvc.ToUpper())||s.Id==int.Parse(textboxmvc)); 
 
    } 
 
     return View(student); 
 
} 

它显示了这个问题:

Server Error in '/' Application. 
LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
 
Exception Details: System.NotSupportedException: LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression. 
 
Source Error: 
 
 
Line 42:                     </tr> 
Line 43:  
Line 44:                 <% foreach (var item in Model) { %> 
Line 45:                     <tr> 
Line 46:                     
 
 
Source File: d:\aimen\Projects\Schoo_Project\Schoo_Project\Views\Students\Search.aspx    Line: 44  

请您参考如下方法:

你必须事先解析它。

public ViewResult Search(string textboxmvc) 
{ 
    int parsedId; 
    int.TryParse(textboxmvc, out parsedId); 
    var student = from i in db.StudentSet  select i; 
 
    if (!String.IsNullOrEmpty(textboxmvc)) 
    { 
        student = student.Where(s => s.FirstName.ToUpper().Contains(textboxmvc.ToUpper()) 
                                   || s.LastName.ToUpper().Contains(textboxmvc.ToUpper())||s.Id==parsedId); 
 
    } 
 
     return View(student); 
 
}