이런 종류의 UI를 수행하는 방법이 있습니다. 어떻게하는지 보여 드리겠습니다. 이를 위해서는 부분 뷰와 아약스 호출을 사용해야합니다.
먼저 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; }
}
이제 연락처 목록을 생성하는 부분보기를 추가해야합니다. 여기에 내가 지금 당신이 부분 뷰를 반환하는 또 다른 ActionResult 방법을 추가 할 필요가
@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>
}
_Contacts.cshtml
라는 부분 뷰를 추가했다.
[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