0

我有一个复杂的实体用户:

    public class User : BaseEntity
    {        
    public virtual Taxi Taxi { get; set; }  --> That is why i call it "complex"
    public virtual string Login { get; set; }           
    public virtual string Password { get; set; }  
    }

其中 Taxi 是 User 的父级(Taxi has-many Users):

    public class Taxi : BaseEntity
    {
      public virtual string Name { get;  set; }
      public virtual string ClientIp { get;  set; }
    }

BaseEntity 由 public virtual int Id { get; 私人套装;}

尝试编辑用户时出现问题

    [Authorize]  
    public ActionResult ChangeAccountInfo()
    {
        var user = UserRepository.GetUser(User.Identity.Name);
        return View(user); 
    }

我的 ChangeAccountInfo.aspx

        <fieldset>
        <legend>Fields</legend>
        <%  %>
        <div class="editor-label">
            <%: Html.LabelFor(model => model.Login) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.Login) %>
            <%: Html.ValidationMessageFor(model => model.Login) %>      
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Password) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.Password) %>
            <%: Html.ValidationMessageFor(model => model.Password) %>
        </div>  

         <div class="editor-field">
            <%: Html.HiddenFor(model => model.Taxi.Name)%>               
        </div>     

        <p>
            <input type="submit" value="Save" />
        </p>
       </fieldset>

发布更改:

    [Authorize]
    [HttpPost]
    public ActionResult ChangeAccountInfo(User model)
    {
        if (ModelState.IsValid)
        {
            UserRepository.UpdateUser(model); 

            return RedirectToAction("ChangeAccountInfoSuccess", "Account");
        }

        return View(model);
    }

但是,(用户模型)参数有 User.Id == 0 --> 用户实体在编辑之前有 5 个
User.Login == "my new login" User.Password
== "my new password"
User.Taxi.Id = = 0 --> User.Taxi 实体在编辑前有 3 个
User.Taxi.Name == "old hidden name"
User.Taxi.ClientIp == null --> User 实体在编辑前有 192.168.0.1

问: 是否可以不使用标签“隐藏”标记实体的所有字段(应该在我的 UpdateUser 中)但在我的 HttpPost 方法中仍然保持不变?例如不是 User.Taxi.ClientIp = null,而是 User.Taxi.ClientIp = 192.168.0.1

我正在使用 nhibernate,如果它重要的话。

4

2 回答 2

1

并非没有一些繁重的工作。我不确定 nhibernate 是否关心它是否是同一个确切的实例;您可能只需要保留实体的 ID 即可让您的表单正常工作。

如果第二种情况为真,您需要做的就是在表单中创建一个隐藏字段来存储模型的 id。MVC 将完成其余的工作。只需将其放入顶部的表单中即可:

<%= Html.HiddenFor(model => model.Id) %>

您可以指定(通过白名单或黑名单)在表单中可以/不能编辑哪些属性,如果您担心人们会被黑客入侵(而且您应该这样做)。

于 2010-05-05T14:35:44.867 回答
0

Will 建议的答案最符合我的问题:
编辑您的实体
- 为您的视图提供您要编辑的实体身份
- 在隐藏字段中发布您的带有身份的模型(在我的情况下,我不能使用 model.Id 私有setter 因为 nhib 映射设置)
- 在 httpPost 方法中使用 GetById(idFromHiddenField) 来检索您的 entityFromDatabase
- 使用 UpdateModel(entityFromDatabase) - 这将合并旧版本(entityFromDatabase)和新版本的实体
- 然后 ISession.Update(entityFromDatabase) 持续存在更改为数据库

于 2010-05-05T20:40:32.260 回答