4

我想了解更多關於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">&times;</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文章。然後如何處理從該帖子返回的數據。那麼如何將新的持久記錄添加到選擇列表中?

我知道標籤沒有傳遞給控制器​​方法,因爲它沒有綁定到任何類型的模型,而是因爲我在父視圖上使用視圖模型,我不知道我會如何處理這裏也是。

回答

1

爲了在您需要發佈新的標籤Name使用AJAX,到保存BlogTag並返回其新ID值的控制方法的觀點動態地添加新BlogTag。你的控制器的方法會是這樣的

[HttpPost] 
public JsonResult CreateTag(string name) 
{ 
    BlogTag tag = new BlogTag(){ Name = name }; 
    db.BlogTags.Add(tag); 
    db.SaveChanges(); 
    return Json(tag.ID); 
    // If the above code could result in an error/exception, catch it and return 
    // return Json(null); 
} 

然後在視圖中,處理對話框提交按鈕後的值,並更新標籤列表

var url = '@Url.Action("CreateTag")'; 
var tagList = $('#SelectedTags'); 
$('#tag-form').submit(function() { 
    var tagName = $('#Name').val(); 
    $.post(url, { name: tagName }, function(id) { 
    if (id) { 
     // add the new tag to the list box 
     tagList.append($('<option></option>').val(id).text($('#Name').val())); 
     // trigger the chosen update 
     tagList.trigger("chosen:updated"); 
    } else { 
     // Oops - display an error message? 
    } 
    }).fail(function (result) { 
    // Oops - display an error message? 
    }); 
    return false; // cancel the default submit 
}); 

附註:我會建議你創建一個查看模型BlogTagVM(包含具有驗證屬性的Name的屬性)以及生成對話框html的關聯分部視圖(如_AddBlogTag.cshtml),以便在主視圖中可以使用@Html.Partial("_AddBlogTag", new BlogTagVM()),這將允許您使用強類型html助手,幷包括de客戶端驗證。

另請注意,嵌套的<form>元素無效,因此請確保對話框的html位於視圖的主<form>標記之外。

+0

我可以看到這是如何工作和實施它。我可以看到使用Firefox開發人員工具將新選項添加​​到html源代碼的選項列表中(看起來我比我第一次想到的更接近解決方案)。但是,選擇選擇的UI元素在頁面刷新之前似乎不會識別它。所以爲了澄清 - 它附加了html源文件'

+0

取消,我讀了選擇的網站,並且有一個更改/更新事件,你可以觸發哪個是$( 「#SelectedTags」)。trigger(「chosen:updated」);'taglist.append('後面的'''''''''''''''').val(ID).text(tagName.val()));'如果你可以詳細說明關於如何處理未能將標記保存在分貝中的問題,我很樂意+1!乾杯。 – paulpitchford

+0

我已經有'tagList.trigger(「選擇:更新」)行;'在我的答案:)。有幾種處理失敗的方法 - 你可以'返回Json(null)'並在腳本中檢查if(id){// add option} else {// oops}'或者你可以返回一個'HttpStatusCodeResult'指示錯誤,然後添加'.fail(function(result){// oops});'到'$ .post'函數 - 我已經用示例更新了答案 –

0

我正在做類似的事情,我想這可能會有幫助。在我的情況下,我正在將一個列表中的值「移動」到另一個列表中(從「可用」到「已用」),然後保存「已用」列表的值。無論如何,在控制器中,「used」列表顯示爲一個字符串數組。這裏是我的代碼:

 public ActionResult PinchHit(FormCollection form, LineupViewModel lvm, String[] UsedPlayers) 
     { 
[Snip] 
      if (ModelState.IsValid && lineupResults.IsValid) 
      { 
[Snip] 
       foreach (String usedID in UsedPlayers) 
       { 
        gameState.HomeUsedPlayersIDs.Add(Convert.ToInt32(usedID)); 
       } 
       uow.Repository<GameState>().Update(gameState); 
       uow.SaveChanges(); 
       return RedirectToAction("Index", "GameSummary"); 
      } 
[Snip] 
      return View(lvm2); 
     } 

希望有所幫助。

每我的評論:

這裏是我使用無需重新加載頁面,從數據庫中檢索數據的AJAX回撥機制,你可以用它來保存數據到數據庫,而不是。

<script type="text/javascript"> 
     function getPositions(id, control) { 
      $.ajax({ 
       url: "@Url.Action("GetPositions", "Lineup")", 
       data: 
       { 
        id: id 
       }, 
       dataType: "json", 
       type: "POST", 
       error: function() { 
        alert("An error occurred."); 
       }, 
       success: function (data) { 
        $(control).html(""); 
        $.each(data, function (i, item) { 
         $(control).append("<option value=\"" + item.Value + "\">" + item.Text + "</option>"); 
        } 
        ); 
       } 
      }); 
     } 
</script> 

然後控制器:

[HttpPost] 
    public ActionResult GetPositions(int id) 
    { 
     Player player = uow.Repository<Player>().GetById(id); 
     if (player == null) 
     { 
      return (null); 
     } 
     List<SelectListItem> positionList = new SelectList(player.Positions, "ID", "ShortName").ToList(); 
     return Json(positionList); 
    } 

漂亮的標準的東西真的。

+0

謝謝,但我認爲這會導致頁面加載,是否正確?如果可能,我儘量避免這種情況。我知道我可以發表一個表格,並重新加載視圖與預先輸入的字段和更新選擇列表,但我希望做到客戶端。 – paulpitchford

+0

我正在做的是收集客戶端的所有值,然後在發佈期間持久保留它們(當用戶完成所有更改並單擊提交按鈕時)。您要求在每次添加更改時都要保持這些更改沒有重新加載頁面的標籤?在這種情況下,您需要對JSON方法進行AJAX回調。我會編輯我的答案。 – Duston

+0

非常感謝,但作爲一個完整的初學者,尤其是與JS,它不是足夠的信息,讓我到我需要的地方,我想。我有一個窗體打開,但我的表單數據不會傳遞到我的控制器,我不知道如何處理新的標記,一旦它保持。 (我以爲我比以前更接近我實際上!) – paulpitchford

相關問題