[英]ASP.NET MVC Model Binding in Complex ViewModel Object
這是我的復雜ViewModel
public class OperationStudyInputViewModel
{
public OperationStudy OperationStudy { get; set; }
public FileUpload FileUploads { get; set; }
public IEnumerable<string> Attachments { get; set; }
public IEnumerable<string> Folders { get; set; }
}
這是OperationStudy模型
public class OperationStudy
{
public int OperationStudyId { get; set; }
public string SpCategoryId { get; set; }
//Here is some Other Properties
}
這是OperationStudyInput()發布方法
[HttpPost]
public ActionResult OperationStudyInput([Bind(Exclude = "SpCategoryId")] OperationStudyInputViewModel inputViewModel, IEnumerable<HttpPostedFileBase> multiplefiles)
{
// some Necessary codes Here
_dbContext.OperationStudies.Add(inputViewModel.OperationStudy);
_dbContext.SaveChanges();
}
我想排除SpCategoryId
在inputViewModel(inputViewModel.OperationStudy)在OperationStudyInput(從OperationStudy)發表mehtod。 我已經嘗試了前面的代碼,但是它沒有按預期工作!
任何幫助請!
我建議區分視圖模型和數據模型。 如果您直接返回,則可能會導致意外的安全問題(突然在后端添加字段將導致該字段暴露於Web)。 因此,我要做的就是創建許多Web模型,例如,可以在Web后面添加后綴,並在每次需要返回時進行映射。
這將在視圖層和BI層之間提供良好的隔離。 為了幫助您實現這一目標,可以使用諸如AutoMapper
框架。 這不是必需的,但可以幫助您進行粗略映射。
您可能會認為這是一個矯kill過正的方法,但是請相信我,從長遠來看,您將看到這種方法的優點。 您也可以在Google上搜索有關分離主題的更多信息。
PS:我不會建議從其他模型中刪除從模型中刪除數據的任何技巧。 這對我來說似乎是一種非常脆弱的方法。
您可以像這樣在類上指定Bind屬性:
[Bind(Exclude = "SpCategoryId")]
public class OperationStudy
{
public int OperationStudyId { get; set; }
public string SpCategoryId { get; set; }
}
但是,我建議創建並使用單獨的ViewModel進行綁定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.