动态添加类别ASP.Net 4 MVC#

动态添加类别ASP.Net 4 MVC#,c#,jquery,asp.net,asp.net-mvc-3,razor,C#,Jquery,Asp.net,Asp.net Mvc 3,Razor,我正在用ASP.NET4、MVC3、Razor和C#创建一个博客。 有两张独立的桌子。1用于实际博客文章和类别的关系表。 类别显示为下拉列表。 我想添加使用Ajax添加新类别的功能,这样用户就不会丢失他们在表单中输入的内容。 实现这一目标的最佳方式是什么? 这是我现在拥有的 控制器代码 public ActionResult Create() { ViewBag.category_id = new SelectList(_db.Categories, "id", "cat

我正在用ASP.NET4、MVC3、Razor和C#创建一个博客。 有两张独立的桌子。1用于实际博客文章和类别的关系表。 类别显示为下拉列表。 我想添加使用Ajax添加新类别的功能,这样用户就不会丢失他们在表单中输入的内容。 实现这一目标的最佳方式是什么? 这是我现在拥有的

控制器代码

public ActionResult Create()
    {
        ViewBag.category_id = new SelectList(_db.Categories, "id", "category_name");
        return View();
    } 
剃刀视图

@model NPP.Models.News

@{
    ViewBag.Title = "Create News Item";
}

<h2>Create News Item</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>

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>News</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.news_title, "Title")
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.news_title)
        @Html.ValidationMessageFor(model => model.news_title)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.news_content, "Content")
    </div>
    <div class="editor-field">
        @Html.TextAreaFor(model => model.news_content)
        @Html.ValidationMessageFor(model => model.news_content)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.news_teaser, "Teaser (optional)")
    </div>
    <div class="editor-field">
        @Html.TextAreaFor(model => model.news_teaser)
        @Html.ValidationMessageFor(model => model.news_teaser)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.category_id, "Category")
    </div>
    <div class="editor-field">
        @Html.DropDownList("category_id", String.Empty)
        @Html.ValidationMessageFor(model => model.category_id)
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@model NPP.Models.News
@{
ViewBag.Title=“创建新闻项”;
}
创建新闻项
@使用(Html.BeginForm()){
@Html.ValidationSummary(true)
新闻
@Html.LabelFor(model=>model.news_title,“title”)
@EditorFor(model=>model.news_title)
@Html.ValidationMessageFor(model=>model.news_title)
@Html.LabelFor(model=>model.news\u content,“content”)
@Html.TextAreaFor(model=>model.news\u内容)
@Html.ValidationMessageFor(model=>model.news\u内容)
@LabelFor(model=>model.news\u摘要,“摘要(可选)”)
@Html.TextAreaFor(model=>model.news\u摘要)
@Html.ValidationMessageFor(model=>model.news\u摘要)
@Html.LabelFor(model=>model.category_id,“category”)
@Html.DropDownList(“category_id”,String.Empty)
@Html.ValidationMessageFor(model=>model.category\u id)

} @ActionLink(“返回列表”、“索引”)

提前谢谢你的帮助。我的布局页面包括我更喜欢使用的jquery。

添加另一个Controller方法以返回类别列表,类似于:

public JsonResult Categories()
{
  return Json(DB.GetCategorys(), JsonRequestBehavior.AllowGet);
}
$.ajax({
  url: 'http://myserver/myapp/mycontroller/Categories',
  success: function(data) {
       $('#dropCategorys').html('');
       $.each(data, function(i, e) {
           $('#dropCategorys').append('<option value="' + 
              e.category_id + '">' + e.category_name + '</option>');
       }
  }
});
然后在客户端,使用ajax获取类别并将其绑定到下拉列表中,如:

public JsonResult Categories()
{
  return Json(DB.GetCategorys(), JsonRequestBehavior.AllowGet);
}
$.ajax({
  url: 'http://myserver/myapp/mycontroller/Categories',
  success: function(data) {
       $('#dropCategorys').html('');
       $.each(data, function(i, e) {
           $('#dropCategorys').append('<option value="' + 
              e.category_id + '">' + e.category_name + '</option>');
       }
  }
});
$.ajax({
网址:'http://myserver/myapp/mycontroller/Categories',
成功:功能(数据){
$('#dropcategoris').html('');
$。每个(数据、功能(即){
$(“#dropcategoris”)。追加(“”+e.category_name+“”);
}
}
});

这不会保存您当前选择的项目,但您可以在清除列表之前检查该项目,然后将其重置。

通过AJAX单独创建类别不是您唯一的选择。然后您可以拥有如下视图模型:

public class CategoryViewModel
{
    public string name { get; set; }
    public int id { get; set; }
}

public class CreateNewsViewModel
{
    public string news_title { get; set; }
    public string news_content { get; set; }
    public string news_teaser { get; set; }
    public string CategoryViewModel category { get; set; }
}
[HttpPost, ActionName("Create")]
public ActionResult DoCreate(CreateNewsViewModel model)
{
    if (ModelState.IsValid)
    {
        if (model.category.id == 0)
        {
            // create your new category using model.category.name
        }

        // create an entity from the model and save to your database

        return RedirectToAction("Index", "News"); // do whatever you wish when you're done
    }

    return View("Create", model); // show Create view again if validation failed
}
在“类别”字段中更改视图:

<div class="editor-label">
    @Html.LabelFor(model => model.category, "Category")
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.category.id, ViewBag.category_id)
    @Html.EditorFor(model => model.category.name) <!-- only show when creating a new category -->
    @Html.ValidationMessageFor(model => model.category)
</div>
这或多或少是我脑子里想不出来的,所以如果我把任何部分搞糟了,请告诉我