2013-10-01 29 views
2

這些都是我的模型類:如何從MVC4的視圖中編輯父級的屬性?

/// <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的查看代碼的一部分:

<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控制器是如何工作的。

有什麼建議嗎?

在此先感謝!

+0

你將更改後的值發回您的控制器方法?如果是這樣,你的控制器方法是什麼樣的? – mickfold

+0

您可以請檢查您的輸出HTML文本框的ID和名稱屬性是什麼? MVC通過這些名稱映射傳遞給控制器​​的實體。如果名稱錯誤,可能需要在CSHTML中手動設置。 –

+0

輸出HTML似乎是正確的: Kutyel

回答

1

首先,必須從DocumentLineDeliveryNoteLineMetadata繼承:

internal class DeliveryNoteLineMetadata : DocumentLine 

然後,只需更改getter和setter使用基本值(也加入new隱藏base屬性):

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

它表示'對象'不包含DocumentNumber的定義。 :S – Kutyel

+0

@Kutyel,道歉,您需要'new'關鍵字來隱藏基本屬性。另外,您需要'DeliveryNoteLineMetadata'繼承'DocumentLine'。看到我的編輯 – mattytommo

+0

恐怕這個解決方案不起作用:'(當我調試delivery的值時,基本屬性,包括DocumentNumber,不會改變。> _ < – Kutyel

相關問題