我想了解更多關於MVC 5的內容,所以我正在爲自己編寫一個博客網站以瞭解更多信息。在MVC 5客戶端添加項目選擇列表ASP
我已經設置了標籤的選擇列表,並希望能夠從創建博客條目頁面添加新標籤,而不必記住在創建新帖子之前設置標籤。我正在考慮顯示引導模式窗口的「添加標籤」按鈕,用戶可以在其中添加新標籤。
這裏是我的控制器操作:
public ViewResult CreateBlogPost()
{
CreateEditBlogViewModel viewModel = new CreateEditBlogViewModel();
viewModel.BlogPost = new Core.BlogPost();
viewModel.BlogPost.ShortBody = "<p>Something short and sweet to describe the post</p>";
viewModel.BlogPost.Body = "<p>Enter something blog worthy here...</p>";
viewModel.Tags = new SelectList(_blogRepo.BlogTags(), "Id", "Name");
viewModel.Categories = new SelectList(_blogRepo.BlogCategories(), "Id", "Name");
return View(viewModel);
}
這裏是在視圖中的HTML:
<div class="row">
<div class="form-group">
@Html.LabelFor(m => m.BlogPost.Tags, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.ListBoxFor(m => m.SelectedTags, Model.Tags, new { @class = "form-control chosen-select", @data_placeholder = "Start typing to see a list of tags" })
</div>
</div>
</div>
<div class="row">
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#tagModal">
Add Tag
</button>
</div>
這裏是我的模態窗口局部視圖:
@using (Html.BeginForm("SaveTag", "Home", FormMethod.Post, new { id = "tag-form" }))
{
@Html.AntiForgeryToken()
<!-- Modal -->
<div class="modal fade" id="tagModal" tabindex="-1" role="dialog" aria-labelledby="tagModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="tagModalLabel">Enter a name for a new tag</h4>
</div>
<div class="modal-body">
<input type="text" id="Name" placeholder="Enter a new tag name" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
}
是否有可能在客戶端添加標籤,將其保存到數據庫中,然後將其添加到我的標籤選擇列表機智豪特刷新頁面?
PS:僅供參考我使用從here選擇的多選。
@section scripts {
<script type="text/javascript" src="~/Scripts/chosen.jquery.min.js"></script>
<script type="text/javascript">
$(".chosen-select").chosen()
</script>
}
編輯:我已經更新了所有,使視圖給用戶的模式窗口中輸入新的標籤名稱的代碼的問題。我只是不確定如何發佈不離開頁面導航,所以我猜測需要某種類型的Ajax文章。然後如何處理從該帖子返回的數據。那麼如何將新的持久記錄添加到選擇列表中?
我知道標籤沒有傳遞給控制器方法,因爲它沒有綁定到任何類型的模型,而是因爲我在父視圖上使用視圖模型,我不知道我會如何處理這裏也是。
我可以看到這是如何工作和實施它。我可以看到使用Firefox開發人員工具將新選項添加到html源代碼的選項列表中(看起來我比我第一次想到的更接近解決方案)。但是,選擇選擇的UI元素在頁面刷新之前似乎不會識別它。所以爲了澄清 - 它附加了html源文件'
取消,我讀了選擇的網站,並且有一個更改/更新事件,你可以觸發哪個是$( 「#SelectedTags」)。trigger(「chosen:updated」);'taglist.append('後面的'''''''''''''''').val(ID).text(tagName.val()));'如果你可以詳細說明關於如何處理未能將標記保存在分貝中的問題,我很樂意+1!乾杯。 – paulpitchford
我已經有'tagList.trigger(「選擇:更新」)行;'在我的答案:)。有幾種處理失敗的方法 - 你可以'返回Json(null)'並在腳本中檢查if(id){// add option} else {// oops}'或者你可以返回一個'HttpStatusCodeResult'指示錯誤,然後添加'.fail(function(result){// oops});'到'$ .post'函數 - 我已經用示例更新了答案 –