2013-06-06 50 views
6

我想用java腳本動態地將項目添加到我的模型中的列表中。我如何讓MVC將新項目綁定到模型?如何在javascript中添加項目到MVC模型?

我的模型:

public class Garage 
{ 
    public string Name{ get; set; } 
    public string Location { get; set; } 
    public IList<Car> Cars{ get; set; } 
} 

public class Car 
{ 
    public string Color{ get; set; } 
    public string Name { get; set; } 
} 

我的看法,它採用了車庫爲模型:

<% using (Html.BeginForm()) 
{%> 
<div id="cars"> 
     <% 
       foreach (var item in Model.Cars) 
       { 
        Html.RenderPartial("CarView", item); 
       } %> 
</div> 
<% } %> 

而且我Carview會它採用了轎車的典範:

<div class="carRow">    

     <%-- Color--%> 
     <%=Html.CustomLabelFor(model => model.Color)%> 
     <%= Html.TextBox(Model.Color) %> 

     <%-- Name--%> 
     <%=Html.CustomLabelFor(model => model.Name)%> 
     <%= Html.TextBox(Model.Name) %> 
</div> 

加入當一個新車,我使用AJAX調用,並將其添加到HTML。 的AJAX使用此方法控制器:

public ViewResult NewCar() 
    { 
     return View("CarView"); 
    } 

我的Java腳本調用Ajax:

  $('.addCarButton').click(function() { 
      $.ajax({ 
       url: "<%= Url.Action("CreateCars") %>", 
       cache: false, 
       success: function (html) { $("#cars").append(html); } 
      }); 
      return false; 
     }); 

這很好地呈現HTML,但它並不車添加到汽車的列表。

這怎麼辦?

+0

它不需要添加一個JavaScript點擊處理程序。這些變量已經在MVC中提供。 – spons

回答

9

你可以看看following article,其中史蒂文桑德森提供了一步一步教程如何實現這一點。

2

我意識到這是一個老問題,但在嘗試重新Steven Sanderson's BeginCollectionItem上述建議後,和一些其他潛在的解決方案,我沒有得到很遠(新項目不會發布)。 BeginCollectionItem在理論上似乎是一個很好的解決方案,但它不會發布新項目,並且它對列表項目的格式有意想不到的影響。

溶液卷繞是令人驚訝的簡單,並且不需要任何外部庫(超出的JQuery)。這在ASP.NET MVC5中適用於我。

  1. 爲行項目創建一個編輯器模板。

路徑:查看/共享/ EditorTemplate/NuggetSourceDto.cshtml

@model [namespace].NuggetSourceDto 

@{ 
    ViewBag.Title = "NuggetSourceDto"; 
} 

<li [email protected]> 
    @Html.HiddenFor(t => t.Id) 
    @Html.TextBoxFor(s => s.Url, new { @class = "form-control", autofocus = "autofocus" }) 
    <a role="button" class="glyphicon glyphicon-remove"></a> 
</li> 
  • 使用上述模板(通過收集以下運行,併爲每個項目生成HTML ):
  • 筆者認爲:

    @Html.EditorFor(m => m.NuggetSources); 
    
  • 當用戶點擊'添加行'按鈕(我的代碼中的'addSourceBtn'),我使用ajax來獲取模板的html。
  • MVC控制器get方法:

    [HttpGet] 
    public PartialViewResult AddBlankSourcesRow() 
    { 
        return PartialView("EditorTemplates/NuggetSourceDto", new NuggetSourceDto()); 
    } 
    

    JS處理程序:

    $(document).ready(function() { 
        $('#addSourceBtn').click(function() { 
         var indexOfNewItem = $('#sourceList li').length; 
    
         $.ajax({ 
          url: '/nugget/AddBlankSourcesRow/', 
          cache: false, 
          success: function (html) { 
           var newItem = $(html); 
           var randId = Math.random() * 10000000; 
           randId = Math.floor(randId); 
           newItem.attr('id', 'newSource__' + randId); 
           newItem.find('input').first().attr({ 
            //name: 'NuggetSources[3].Id' 
            name: 'NuggetSources[' + indexOfNewItem + '].Id', 
            id: 'NuggetSources_' + indexOfNewItem + '__Id', 
            value: randId 
           }); 
           newItem.find('input[id^=Url]').attr({ 
            name: 'NuggetSources[' + indexOfNewItem + '].Url', 
            id: 'NuggetSources_' + indexOfNewItem + '__Url' 
           }); 
           $('#sourceList').append(newItem); 
          } 
         }); 
         return false; 
        }); 
    }); 
    

    在所有這一切的關鍵所在是要確保新插入的元素有每個屬性名稱屬性包括集合的名稱和有效索引:

     newItem.find('input').first().attr({ 
          //name: 'NuggetSources[3].Id' 
          name: 'NuggetSources[' + indexOfNewItem + '].Id' 
         }); 
         newItem.find('input[id^=Url]').attr({ 
          name: 'NuggetSources[' + indexOfNewItem + '].Url' 
         }); 
    

    如果沒有此項,MVC控制器中的新項目將被忽略。

    該解決方案僅處理添加新行。對於刪除操作,因爲索引很重要,所以一種解決方案是向服務器發出刪除請求,然後重新加載列表,或者只修復js中的現有索引。

    相關問題