c# - ASP.Net MVC - 带集合的模型,提交

标签 c# asp.net-mvc entity-framework

我有一个看起来像的模型

public class Patient
{
    private ICollection<Refill> _refills = new List<Refill>();
    public int Id { get; set; }
    public string FirstName { get; set; }
                  
    public virtual ICollection<Refill> Refills
    {
        get { return _refills; }
        set { _refills = value; }
    }
}

public class Refill
{
    public int Id { get; set; }

    public RefillActivityStatus RefillActivityStatus { get; set; }
    public DateTime? RefillDate { get; set; }
    public RefillType RefillType { get; set; }
    public string RXNumber { get; set; }
}

这是我正在尝试做的事情。我想在 View 中填充这些以及当用户单击保存更改时。我想保存 Entity Framework 。我遇到的问题是我这样做的观点

@foreach (var m in Model.Refills)
{
     @Html.HiddenFor(model=>m.Id)
     <div class="editor-label">
         @Html.LabelFor(model => m.RXNumber)
     </div>
     <div class="editor-field">
         @Html.EditorFor(model => m.RXNumber)                                  
     </div>     
}

我想在 Controller 中做这样的事情

[HttpPost]
public ActionResult Details(Patient patient)
{
    Patient p = db.Patients.Find(patient.Id);
    db.Entry(p).State = EntityState.Modified;
    db.Entry(p).CurrentValues.SetValues(patient);
    // Would include Refill changes too but it doesn't
    db.SaveChanges();

    return View(p);
}

但是,Refills 不会在 HttpPost 上传播。它只是空的,我需要做什么来修复它?

最佳答案

在你的 foreach 中试试这个:

@for (int i = 0; i < Model.Refills.Count(); i++)
{
    @Html.Hidden("Refills[" + i + "].Id", Model.Refills[i].Id)
    <div class="editor-label">
        @Html.Label("Refills[" + i + "].RXNumber", Model.Refills[i].RXNumber)
    </div>
    <div class="editor-field">
        @Html.Editor("Refills[" + i + "].RXNumber")
    </div>     
}

关于c# - ASP.Net MVC - 带集合的模型,提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14563471/

相关文章:

javascript - CKEditor 问题 : How to apply custom css to CKEditor

asp.net-mvc - 如何避免开放重定向漏洞并在成功登录时安全重定向(提示 : ASP. NET MVC 2 默认代码存在漏洞)

c# - 在 Entity Framework 支持的 Web API 2 POST 调用中返回一个对象以及 409 冲突错误?

c# - 存储库、删除对象、模型与 ID

c# - 以编程方式将 Entity Framework 数据库重置为 $InitialDatabase

c# - "InvalidOperationException: IDX20803: Unable to obtain configuration from: ' [PII 被隐藏] '"

c# - 在 MVVM 之后从 WPF 中的组框确定选中的单选按钮

c# - 有没有办法在 C# 中将数据库设置为单用户模式?

C# 和 MySQL - 字符串替换

c# - 从表中获取值作为引用