【问题标题】:ASP.NET 4.5 - Modelbinding on User Control with GridviewASP.NET 4.5 - 使用 Gridview 对用户控件进行模型绑定
【发布时间】:2014-01-29 13:01:15
【问题描述】:

如果之前有人问过这个问题,我深表歉意,但我正在开发一个带有Gridview 的用户控件。 (我这样做的原因是我想在我的应用程序的不同页面上重复使用控件)。

我想在这个Gridview 上使用modelbinding,但是当我尝试启用它时,它不起作用。 当我尝试编译时,它给了我以下错误:

'IsValid' is not a member of 'System.Web.ModelBinding.ModelState'.

'AddModelError' is not a member of 'System.Web.ModelBinding.ModelState'.

<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="test.ascx.vb" Inherits="Octoplus.test" %>
<asp:GridView ID="GridView1" runat="server" ItemType="Octoplus.OrderHeader" UpdateMethod="GridView1_UpdateItem">

Imports System.Web.ModelBinding
Inherits System.Web.UI.UserControl

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub

' The id parameter name should match the DataKeyNames value set on the control
Public Sub GridView1_UpdateItem(ByVal id As Integer)
    Dim item As Octoplus.OrderHeader = Nothing
    ' Load the item here, e.g. item = MyDataLayer.Find(id)
    If item Is Nothing Then
        ' The item wasn't found
        ModelState.AddModelError("", String.Format("Item with id {0} was not found", id))
        Return
    End If
    TryUpdateModel(item)
    If ModelState.IsValid Then
        ' Save changes here, e.g. MyDataLayer.SaveChanges()

    End If
End Sub

有人有想法吗?

提前致谢。

【问题讨论】:

    标签: c# asp.net .net gridview model-binding


    【解决方案1】:

    您收到该错误是因为 ModelState 不是 UserControl 的成员,而是 Page 的成员。所以你必须使用 UserControl 中的 Page 属性来访问 ModelState 值:

    If Page.ModelState.IsValid Then
        ' Save changes here, e.g. MyDataLayer.SaveChanges()
    End If
    

    【讨论】:

      【解决方案2】:

      命名空间System.Web.ModelBinding中的ModelState类根本没有IsValidAddModelError这样的属性...

      您可以阅读此类here 的可用属性和方法。

      您的问题是您试图在 ASP.NET WebForms 应用程序中使用来自System.Web.MvcModelState

      System.Web.Mvc 命名空间(适用于 ASP.NET MVC 项目)中的ModelState 确实具有IsValidAddModelError 属性,您可以阅读有关here 的信息。

      【讨论】:

      • 非常感谢您的回答。
      • 奇怪的是,当我只是创建一个带有 Gridview 的空 Webform 并在该控件上启用 Modelbinding 时,它并没有给我错误。我确实注意到 ModelState 来自命名空间:System.Web.Modelbinding.ModelstateDictionary。
      猜你喜欢
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-24
      • 1970-01-01
      相关资源
      最近更新 更多