我的模型的动态字段 - ASP.NET MVC 3

本文关键字:ASP NET MVC 字段 模型 动态 我的 | 更新日期: 2023-09-27 18:31:00

我想编辑特定字段的数据。例如,我遇到的问题是字段名称是一个字符串。

在我看来,我有这样的参数:

<div class="editable" id="cnso">@Model.cnso</div>

我得到该字段并使用 jeditable 通过 Ajax 调用我的控制器:

$('.editable').editable('/Req/UpdateField', {
    tooltip: 'Click to edit...',
    submitdata : {
        nreqid : function() {
            return $("#nreqid").val();
        }
    }
});

我的控制器在字符串 id 中获取了字段的名称 (cnso)。问题是更新我的模型。我的控制器的一些代码。

public string UpdateField(string id, string value, int nreqid)
{
    /*
     *        id - id of the field. This value can be used on the
     *             server side to determine what property of the
     *             company should be updated.
     *     value - text that is entered in the input field.
     *    nreqid - this is additional parameter that will
     *             be added to the request. Value of this parameter
     *             is a value of the hidden field with an id "ReqId".
     */
    ModelState.Clear();
    if (ModelState.IsValid)
    {
        //db.Entry(req).State = EntityState.Modified;
        //db.SaveChanges();
        Req req = db.Req.Find(nreqid);
        req."id" = "2";  // <--- Problem here !!!
    }
}

我的模型对象 Req 具有字段cnso,而我的id字符串具有"cnso",那么如何从字符串 ID 中选择cnso呢?

我的模型的动态字段 - ASP.NET MVC 3

使用反射,您可以执行以下操作:

Type t = typeof(Req);
PropertyInfo p = t.GetProperty(id);
if(p != null)
    p.SetValue(req, "2", null);

或者,如果没有太多属性,则可以对所需的所有属性执行不同的"更新"操作。我不知道您需要这样做的情况,但是一次更新表中的各个属性可能不是最好的设计。