2012-06-19 5 views
1

ASP.Net 4, MVC 3, Razor 및 C#으로 블로그를 만드는 중입니다. 2 개의 별도 테이블이 있습니다. 실제 블로그 포스트는 1이고 카테고리는 관계 테이블입니다. 카테고리가 드롭 다운으로 표시됩니다. Ajax를 사용하여 새 범주를 추가하는 기능을 추가하여 사용자가 이미 양식에 입력 한 내용을 잃지 않도록하고 싶습니다. 이 작업을 수행하는 가장 좋은 방법은 무엇입니까? 여기가 지금 있습니다. 사전에 어떤 도움카테고리 추가 동적으로 ASP.Net 4 MVC3 C#

컨트롤러 코드

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> 

감사합니다. 내 레이아웃 페이지에는 jquery가 포함되어 있습니다. 뭔가를 같이 당신의 카테고리를 얻기 위해, 그리고 클라이언트 측에서 사용 아약스를

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

아래로 당신의 하락에 바인딩 :

답변

2

, 뭔가를 당신에게 카테고리의 목록을 반환하는 또 다른 CONTROLER 방법을 추가

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

이것은 현재 선택한 항목을 저장하지 않지만 목록을 지우기 전에 항상 확인하고 나중에 다시 설정할 수 있습니다.

0

AJAX를 통해 카테고리를 별도로 만드는 것이 유일한 옵션은 아닙니다.

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

이이

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; } 
} 
이 카테고리 필드에서보기를 변경

: 당신은 다음과 같은 뷰 모델을 가질 수있다 내 머리 꼭대기에서 다소 벗어나므로 내가 어떤 부분을 ollocks 거리게하는지 알려주지.