有一种方法可以实现这种 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);
});
});
});
希望你能得到这个。