如何从MVC4中的视图编辑父级属性?

时间:2013-10-01 11:23:40

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor

这些是我模型的类:

/// <summary>
/// States the base implementation for all document lines in a purchasing module.
/// </summary>
public class DocumentLine : Keyed
{
    /// <summary>
    /// Document number of the document line.
    /// </summary>
    [Display(ResourceType = typeof(Resources.ApplicationResources), Name = "DocumentNumber")]
    public string DocumentNumber { get; set; }

    ...
}

/// <summary>
/// Defines a line of a Delivery Note document.
/// </summary>
[MetadataType(typeof(DeliveryNoteLineMetadata))]
public class DeliveryNoteLine : DocumentLine
{
   ...
    /// <summary>
    /// Internal class for metadata.
    /// </summary>
    internal class DeliveryNoteLineMetadata
    {
        /// <summary>
        /// Adds the RequiredAttribute to the inherited DocumentNumber property.
        /// </summary>
        [Required]
        public string DocumentNumber { get; set; }
    }
}

这是Edit.cshtml的View代码的一部分:

<div class="display-label">
    @Html.LabelFor(model => model.DocumentNumber)
</div>
<div class="editor-field">
    @Html.TextBoxFor(model => model.DocumentNumber, new { @placeholder = @ApplicationResources.DocumentNumber })
</div>

这是我的控制器方法

/// <summary>
/// Handles the POST event for the Edit action, updating an existing TEntity object.
/// </summary>
/// <param name="id">Id of the TEntity object to update.</param>
/// <param name="model">TEntity object with properties updated.</param>
/// <returns>Redirection to the Index action if succeeded, the Edit View otherwise.</returns>
[HttpPost]
public virtual ActionResult Edit(string id, TEntity model)
{
    var request = new RestSharp.RestRequest(Resource + "?id={id}", RestSharp.Method.PUT) { RequestFormat = RestSharp.DataFormat.Json }
        .AddParameter("id", id, RestSharp.ParameterType.UrlSegment)
        .AddBody(model);
    var response = Client.Execute(request);

    // Handle response errors
    HandleResponseErrors(response);

    if (Errors.Length == 0)
        return RedirectToAction("Index");
    else
    {
        ViewBag.Errors = Errors;
        return View(model);
    }
}

这不起作用。 DocumentLine对象的属性DocumentNumber的值不会改变,而且我很难理解MVC4控制器如何在其中工作。

有什么建议吗?

提前致谢!

1 个答案:

答案 0 :(得分:1)

首先,让DeliveryNoteLineMetadata继承DocumentLine

internal class DeliveryNoteLineMetadata : DocumentLine

然后只需更改getter和setter以使用基值(同时添加new以隐藏base属性):

[Required]
public new string DocumentNumber 
{ 
    get 
    { 
        return base.DocumentNumber;
    }
    set
    {
        base.DocumentNumber = value;
    }
}