我是 MVC 的新手。我有一个模型类,它具有另一个类的 List 属性。
public class CustomerModel
{
[Required]
[Display(Name = "Customer Name")]
public string CustomerName { get; set; }
[Required]
public string Company { get; set; }
[Required]
[Display(Name="Contact Details")]
public List<ContactModel> Contacts { get; set; }
}
public class ContactModel
{
[Required]
[Display(Name = "Contact Name")]
public string ContactName { get; set; }
[Required]
[Display(Name = "Contact Number")]
public string ContactNo { get; set; }
}
当我为创建操作创建 View 时,Visual Studio 仅为 ContactName 和 ContactNo 创建标记。
现在的UI是这样的
但我需要这样的用户界面。
有没有办法为联系人属性插入生成标记。或者我是否需要使用 jquery 和自定义 json 调用来执行此类操作。
最佳答案
有一种方法可以实现这种 UI。 我会告诉你如何去做。为此,我们必须使用部分 View 和 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; }
}
现在您必须添加一个局部 View 来生成您的联系人列表。在这里我添加了一个名为 _Contacts.cshtml 的局部 View
@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>
}
现在您必须添加另一个返回分部 View 的 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 数据传递给上述操作方法并检索生成的联系人 View 。
我假设“添加联系人”按钮的 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);
});
});
});
希望你明白这一点。
关于c# - 为具有 List 对象属性的模型生成创建 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21012297/