Skip to main content
 首页 » 编程设计

c#之System.Web.MVC.ModelState 没有 IsValid 的定义

2024年01月26日25jpfss

在我的 MVC 5 应用程序中,我的 DeleteConfirmed ActionResult 中有一个运行良好的 try-catch block 。为了不重复代码,我尝试将以下代码块的指示部分放入 Controller 外部的函数中。我将该函数添加到自定义ErrorLog 类,但是当我这样做时,Intellisense 指示“System.Web.MVC.ModelState 没有 IsValid 的定义。”

This link表示错误来自尝试使用 ModelState 类而不是属性。但是,那篇文章并没有说明应该做什么。

下面是我目前遵循的代码以及我想做的事情。我的问题是我需要做些什么不同的事情才能将 ErrorLog 条目保存到我的数据库表中?

这是我 Controller 中的代码

catch (Exception e) 
{ 
    var _e = new ErrorLog().FillAndSend(e, "Delete", "ChildActionNames"); 
 
    // The following is identical each time I use this catch(Exception e) block 
 
    UnitOfWorkErrorLog uw = new UnitOfWorkErrorLog(); 
    if (ModelState.IsValid) 
    { 
        uw.ErrorLogRepository.Insert(_e); 
        uw.Save(); 
        return View("ErrorManaged"); 
    } 
} 

这就是我想要做的: Controller 中的 Catch block

catch (Exception e) 
{ 
    var _e = new ErrorLog().FillAndSend(e, "Delete", "ChildActionNames"); 
    _e.SaveAlert(_e);  // pass ErrorLog instance to SaveAlert function 
} 

ErrorLog 类中的函数

public void SaveAlert(ErrorLog _e) 
{ 
    // this ErrorLog is already filled when called from controller 
    UnitOfWorkErrorLog uw = new UnitOfWorkErrorLog(); 
    if (ModelState.IsValid) 
    { 
        uw.ErrorLogRepository.Insert(_e); 
        uw.Save();         
    } 
} 

请您参考如下方法:

ModelState是 Controller 基类的一个属性,您的 Controller 都继承自该基类。所以你可以在那里使用它,但不能在 Controller 之外使用它。您可以将模型状态作为参数传递,或者在这种情况下将逻辑保留在 Controller 中更有意义:

if(ModelState.IsValid) 
    _e.SaveAlert(_e);  // pass ErrorLog instance to SaveAlert function 

另外要注意的一点是,将 _e 传递给 SaveAlert 方法是没有意义的。相反,您可以在方法内部使用 this 引用它。