有一種方法可以做這種UI。 我會告訴你如何去做。要做到這一點,我們必須使用部分視圖和ajax調用。
首先,您必須對CustomerModel進行一些更改。
public class CustomerModel
{
[Required]
[Display(Name = "Customer Name")]
public string CustomerName { get; set; }
[Required]
public string Company { get; set; }
[Required]
public ContactModel ContactModel {get;set;}
[Required]
[Display(Name="Contact Details")]
public List<ContactModel> Contacts { get; set; }
}
現在您必須添加一個可生成您的聯繫人列表的部分視圖。在這裏,我添加了名爲_Contacts.cshtml
@model CustomerModel
@for (int i = 0; i < Model.Contacts.Count; i++)
{
<tr>
@Model.Contacts.Count
<td class="editor-field">
@Html.EditorFor(model => model.Contacts[i].ContactName)
</td>
<td class="editor-field">
@Html.EditorFor(model => model.Contacts[i].ContactNo)
@Html.ValidationMessageFor(model => model.Contacts[i].ContactNo)
</td>
</tr>
}
的局部視圖現在你必須添加它返回一個局部視圖,一個又一個的ActionResult方法。
[HttpPost]
public ActionResult GenerateContacts(CustomerModel customer)
{
// Check whether this request is comming with javascript, if so, we know that we are going to add contact details.
if (Request.IsAjaxRequest())
{
ContactModel contact = new ContactModel();
contact.ContactName = customer.ContactMode.ContactName;
contact.ContactNo = customer.ContactMode.ContactNo;
if (customer.Contacts == null)
{
customer.Contacts = new List<ContactModel>();
}
customer.Contacts.Add(contact);
return PartialView("_Contact", customer);
}
}
現在我們爲「添加聯繫人」按鈕編寫一個onclick事件。在那裏,我們將ViewModel數據傳遞給上述操作方法並檢索生成的聯繫人視圖。
我假設「添加聯繫人」按鈕的ID是addContact。在這裏,我將生成的html或聯繫人詳細信息添加到表中。
$(function() {
$("#addContact").click(function() {
$.ajax({
type: "POST",
url: 'Customer/GenerateContacts', // get the link to the controller's action method
data: form.serialize()
})
.success(function (html) {
// this function will automatically called when response of the called ajax call is success
var tableBody = $("#tblContactBody");
tableBody.text(html);
})
.error(function (msg) {
console.log(msg);
});
});
});
希望你得到這個。
看起來像您的添加聯繫人有一個單獨的提交範圍,因此可能您可以使用'contactmodel'爲此創建部分視圖。 – ssilas777