动态添加属性到模型MVC4 [英] Dynamically add a property to model MVC4
问题描述
我是MVC新手,我的要求是我需要设置添加字段来查看。所以为此我做了一个简单的viewmodel,并把我想要渲染的字段。但我不知道如何动态地向类中添加属性。如果发生这种情况,那么我也会简单地整合它。
例如我有一个联系我们的表单,其中包括firstname,lastname等字段。我需要为管理员提供一个设施,系统应该允许他们添加一个新字段以便联系我们表格,如中间名,
Hi,
I am new to MVC, and My requirement is I need to make a facility of adding fields to view. So for that I made a simple viewmodel, and put the fields which I want to render. but I dont know how to add a property to a class dynamically. If that happens then I will simply integrate that too.
e.g. I have a contact us form with fields like firstname, lastname etc. and i need to provide a facility to admin that system should allow them to add a new field for contact us form like middlename,
public class ContactInput
{
[Required]
[StringLength(100)]
[Display(Order = 1)]
public virtual string Name { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[StringLength(254)]
[RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")]
[Display(Order = 2)]
public virtual string Email { get; set; }
[Required]
[StringLength(254)]
[Display(Order = 3)]
public virtual string Subject { get; set; }
[Required]
[StringLength(2000)]
[DataType(DataType.MultilineText)]
[Display(Order = 4)]
public virtual string Message { get; set; }
[Required]
[StringLength(2000)]
[DataType(DataType.MultilineText)]
[Display(Order = 5)]
public virtual string Comments { get; set; }
}
推荐答案
您可以在System.Reflection命名空间下使用ExpandOObject。
一个简短的例子是
You can use ExpandOObject under System.Reflection namespace.
A short example is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection.Emit;
using System.Dynamic;
namespace Home
{
class Program
{
static void Main(string[] args)
{
DynamicClass dc = new DynamicClass();
dynamic dynObj = dc.MethodA();
Console.WriteLine(dynObj.Name); //Using your dynamic properties.
Console.ReadLine();
}
}
class DynamicClass
{
public dynamic MethodA()
{
dynamic dynamicObj = new ExpandoObject();
dynamicObj.Name = "Hi"; //Your own property, you can have any number of properties similar to this.
return dynamicObj;
}
}
}
这篇关于动态添加属性到模型MVC4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!