asp.net - 在 MVC 5 ASP 的客户端添加项目以选择列表

标签 asp.net asp.net-mvc twitter-bootstrap asp.net-mvc-5 jquery-chosen

我正在尝试了解有关 MVC 5 的更多信息,因此我正在为自己编写一个博客网站,以便在我学习的过程中了解更多信息。

我已经为标签设置了一个选择列表,并且希望能够从创建博客条目页面添加新标签,而不必记住在创建新帖子之前设置标签。我正在考虑“添加标签”按钮的行,该按钮显示一个 Bootstrap 模式窗口,用户可以在其中添加新标签。

这是我的 Controller 操作:

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);
}

这是 View 中的 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>

这是我对模态窗口的部分 View :
@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>
}

编辑 :我已经用使 View 为用户提供模式窗口以输入新标签名称的所有代码更新了问题。我只是不确定如何在不离开页面的情况下发布,所以我猜测需要某种 Ajax 发布。然后如何处理从该帖子返回的数据。然后如何将新的持久记录添加到选择列表中?

我知道标签没有传递给 Controller ​​方法,因为它没有绑定(bind)到任何类型的模型,但是当我在父 View 上使用 View 模型时,我也不确定如何在这里处理它。

最佳答案

为了动态添加一个新的BlogTag在 View 中,您需要发布新标签 Name使用ajax,到一个保存BlogTag的 Controller 方法并返回其新的 ID值(value)。您的 Controller 方法将类似于

[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);
}

然后在 View 中,处理对话框提交按钮以发布值并更新标签列表
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 创建一个 View 模型。 (包含 Name 的属性和验证属性)和相关的部分 View (例如 _AddBlogTag.cshtml )生成对话框 html,因此您可以在主视图中使用 @Html.Partial("_AddBlogTag", new BlogTagVM())这将允许您使用强类型的 html 帮助程序,并包括客户端验证。

还要注意嵌套的 <form>元素是无效的 html,因此请确保对话框的 html 在主 <form> 之外 View 的标记。

关于asp.net - 在 MVC 5 ASP 的客户端添加项目以选择列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32949510/

相关文章:

c# - 自定义授权属性在 WebAPI 中不起作用

css - 如何覆盖 Bootstrap ?

php - Bootstrap CDN + WP//如何编辑 '.css’

c# - 基于整数顺序的字符串列表排序

css - asp.net 中的样式 ListView

asp.net-mvc - 更新到 MVC 5 后,iframe 不再工作

asp.net - IIS 配置 - ASP.NET MVC 返回所有请求的默认文档

c# - .Net 是否有任何 "dark launch"框架或库?

jQuery.validate.js 和 asp.net 母版页

html - 如何为 Bootstrap 列表组提供透明背景?