自定义ASP .NET控件中的必需属性 [英] Required Property in Custom ASP .NET Control

查看:118
本文介绍了自定义ASP .NET控件中的必需属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为ASP页面制作一个自Composite WebBoundControl继承的自定义Web控件.我的控件定义中有一个公共属性,必需,如果用户未在ASP页上的控件定义中提供此属性,则它将中断,并且我们将获得异常.我希望编译器在用户忘记提供控件的'runat'属性时发出与警告类似的警告.

I am making a custom web control for my ASP page that inherits from CompositeDataBoundControl. I have a public property in the definition of my control that is required, if the user does not provide this property in the control definition on an ASP page it will break and we will get an exception. I want the compiler to throw a warning similar to the one when a user forgets to provide the 'runat' property of a Control.

验证(ASP.Net):元素'asp:Button'缺少必需的属性'runat'."

"Validation (ASP.Net): Element 'asp:Button' is missing required attribute 'runat'."

这基本上就是我的代码:

Here is basically what my code looks like:

public class MyControl : CompositeDataBoundControl, IPostBackEventHandler
{
    private string _someString;
    public string SomeString
    {
        get { return _someString; }
        set { _someString = value; }
    }

    // Other Control Properties, Functions, Events, etc.
}

我希望"SomeString"成为必需属性,并在构建页面时引发编译器警告.

I want "SomeString" to be a required property and throw a compiler warning when I build my page.

我试图像下面这样在属性上方放置一个Required属性:

I have tried putting a Required attribute above the property like so:

[Required]
public string SomeString
{
    get { return _someString; }
    set { _someString = value; }
}

但这似乎不起作用.

如何生成这样的编译器消息?

How can I generate such a compiler message?

推荐答案

那很简单,在页面加载时,您可以检查属性是否具有某些值.您可以根据属性类型检查是否为Null或Empty. 就像我有这个

Thats quite simple, on page load you can check if the property has some value or not. You can check it for Null or Empty case depending on your property type. like if i have this

private string _someString;
    public string SomeString
    {
        get { return _someString; }
        set { _someString = value; }
    }

在page_load事件中,我将检查

On page_load event i will check if

if(_someString != null && _someString != "")
{ 
    String message = "Missing someString property";
    isAllPropertySet = false; //This is boolean variable that will decide whether any property is not left un-initialised
}

万事如意.

最后

这篇关于自定义ASP .NET控件中的必需属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆