2013-12-11 47 views
0

为所有模型公共属性创建隐藏字段的最佳方法是什么?所有模型属性的隐藏字段

我期待这样的事情:

@Html.HiddenFor(t => t) 
+1

你想这么做的原因是什么? – Shyju

+0

[在C#中通过对象属性循环]的可能重复(http://stackoverflow.com/questions/957783/loop-through-an-objects-properties-in-c-sharp) – Curt

+0

如果您希望这种情况自动发生,你将需要使用反射。 – Maess

回答

2

我想你要做到这一点,当你在编辑界面更新实体记录,以获得其他属性值的原因。您可能正在编辑一些属性(并且只有那些属于您的表单),并且您可能会获得null以用于所有其他不属于表单的属性。

你应该做的是,只将PostID属性保留在表单的隐藏字段中,并在你的HttpPost操作方法中,读取实体并仅更新从表单发送并保存的那些属性。

[HttpPost] 
public ActionResult Edit(Post model) 
{ 
    var existingPost=repositary.GetPost(model.PostID); 

    //Set only the properties posted from form to the existingPost entity 
    existingPost.Title=model.Title; 

    var result= repositary.SavePost(existingPost); 
    return RedirectToAction("PostSaved",new {@id=model.PostID}); 
} 
0

您可以使用http://jqueryui.com/dialog/来显示确认窗口。点击确定按钮指定表单提交。 请看下面的例子:

@using(Ajax.BeginForm("Edit", "Post", null, new AjaxOptions { HttpMethod = "POST" }, new {@id = "frmPost" , enctype = "multipart/form-data" })) 
{ 
    @Html.EditorForModel() 
} 

<div id="dialog">Some confirmation</div>   

<script> 
    $("#dialog").dialog({ 
     modal: true, 
     buttons: { 
      Ok: function() { 
       $("#frmPost").submit(); 
       $("#dialog").dialog('close'); 
      }, 
      Cancel: function() { 
       $(this).close(); 
      } 
     } 
    }); 
</script>