1

I am working on creating a blog with ASP.Net 4, MVC 3, Razor and C#. There are 2 seperate tables. 1 for the actual blog post and a relationship table for categories. The categories displays as a dropdown. I want to add the ability to add a new category using Ajax so the user does not lose what they have already entered into the form. What would be the best way to accomplish this? Here is what I have right now.

Controller Code

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

Razor 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>

Thanks for any help in advance. My layout page includes jquery which I would prefer to use.

4

2 回答 2

2

添加另一个控制器方法以返回类别列表,例如:

public JsonResult Categories()
{
  return Json(DB.GetCategorys(), JsonRequestBehavior.AllowGet);
}

然后在客户端,使用 ajax 获取您的类别并将它们绑定到您的下拉列表,例如:

$.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>');
       }
  }
});

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

于 2012-06-19T23:16:31.377 回答
0

通过 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; }
}

在类别字段中更改您的视图:

<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>

然后您的操作将如下所示:

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

这或多或少在我脑海中浮现,所以让我知道我是否把任何部分都搞砸了。

于 2012-06-19T23:20:02.490 回答