我已經創建了一個ViewModel,其中包含Contact和該Contact的Phones列表。如何將數據從視圖傳遞到MVC中的控制器3
我的目標是爲新聯繫人添加數據,並添加幾個電話,然後通過Controller操作保存。
我編輯了我的聯繫人的腳手架Create.cshtml,爲手機添加了一個網格。增加了一個用於創建手機的JavaScript。到現在爲止還挺好。
問題是當我點擊創建按鈕,我回到控制器,我沒有電話。我如何(在視圖中)將電話行添加到我的IEnumerable中?
編輯: 拿出代碼在視圖中,在這種情況下是不正確的。
我的視圖模型:
public class ContactViewModel
{
public Contact Contact {get; set;}
public IEnumerable<Phone> Phones { get; set; }
}
我的觀點:
@model PilotKibsNet.Controllers.ContactViewModel
<script type="text/javascript" src="../../Scripts/jquery-1.5.1.js"></script>
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript">
function Add() {
$("#tbl > tbody:last").append("<tr><td>" + $("#Number").val() + "</td><td>" + $("#Kind").val() + "</td><td></td></tr>");
$("#Number").val("");
$("#Kind").val("");
}
</script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Contact</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Contact.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Contact.Name)
@Html.ValidationMessageFor(model => model.Contact.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Contact.Address)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Contact.Address)
@Html.ValidationMessageFor(model => model.Contact.Address)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Contact.City)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Contact.City)
@Html.ValidationMessageFor(model => model.Contact.City)
</div>
<legend>Phone numbers</legend>
<label>Number :</label>
@Html.TextBox("Number")
<label>Kind :</label>
@Html.TextBox("Kind")
<input type="button" value="Add" onclick="Add()" />
<table id="tbl">
<tr>
<th>
Phone
</th>
<th>
Kind
</th>
<th></th>
</tr>
<tbody>
</tbody>
</table>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
,然後在由控制器動作,跟有數據,但手機是一個空列表。
[HttpPost]
public ActionResult Create(ContactViewModel contactViewModel)
{
if (ModelState.IsValid)
{
contactViewModel.Contact.id = Guid.NewGuid();
db.Contacts.AddObject(contactViewModel.Contact);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(contactViewModel.Contact);
}
如何讓手機回到服務器?!?
嘗試爲現有的'td所擁有的'td添加名稱。 – Hadas 2012-02-14 09:21:18