2014-01-29 37 views
0

我很抱歉如果之前問過這個問題,但我正在開發一個用戶控件與Gridview。 (我這樣做的原因是因爲我想在我的應用程序的不同頁面上重新使用該控件)。ASP.NET 4.5 - 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 

人有一個想法?

在此先感謝。

回答

0

ModelState類的命名空間System.Web.ModelBinding根本不具備這樣的特性IsValidAddModelError ...

你可以閱讀有關here這個類的可用的屬性和方法。

您的問題是您正嘗試在ASP.NET WebForms應用程序中使用System.Web.Mvc中的ModelState

System.Web.Mvc命名空間中的ModelState(適用於ASP.NET MVC項目)確實具有這樣的性質IsValidAddModelError,你可以讀到here

+0

非常感謝您的支持者。 – SoroTrestal

+0

奇怪的是,當我用Gridview創建一個空的Webform並在該控件上啓用Modelbinding時,它不會給我錯誤。我注意到ModelState來自命名空間:System.Web.Modelbinding.ModelstateDictionary。 – SoroTrestal

1

您正在收到該錯誤,因爲ModelState不是UserControl的成員,而是Page的成員。因此,您必須使用UserControl的Page屬性來訪問ModelState值:

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