2016-03-05 77 views
1

我有简单的数据库ASP.NET MVC中删除项目

CREATE TABLE [dbo].[Date] (
[Id] INT  NOT NULL, 
[Name] NCHAR (10) NULL, 
[Date] DATE  NULL, 
PRIMARY KEY CLUSTERED ([Id] ASC) 
); 

它包含两个记录

enter image description here

我的应用程序加载Name使用Date并在屏幕上显示它的数据库。 enter image description here

的主要问题是,如果我应该使用Remove 列表中删除一个项目,比Save data按钮单击它应该传递给SaveData什么。 我认为我有一个严重的架构错误,因为SaveData函数不知道需要删除的记录。如何解决它?

Index.cshtml

@{ 
ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 
<input type="text" value="02.01.2016"> 
<button data-bind="click: loadData">Load data</button> 
<script src="~/Scripts/knockout-2.2.0.js"></script> 
<table> 
<thead> 
    <tr> 
     <th>name</th> 
    </tr> 
</thead> 
<tbody data-bind="foreach: items"> 
    <tr> 
     <td><input data-bind="value: name" /></td> 
     <td><a href="#" data-bind="click: $root.removeItems">Remove item</a></td> 
    </tr> 
</tbody> 
</table> 
<button data-bind="click: saveData">Save data</button> 
<script> 
function MyViewModel(){ 
    var self = this; 
    self.items = ko.observableArray(); 
    self.removeItems = function (item) { 
     self.items.remove(item); 
    } 
    self.loadData = function() { 

     $.ajax({ 
      cache: false, 

      type: "GET", 

      url: "Home/GetData", 

      data: { "date": $("input").val() }, 

      success: function (data) { 
       $.each(data, function (id, item) { 
        self.items.push({ name: item.Name }); 
       }); 
      }, 

      error: function (response) { 
       alert('eror'); 
      } 
     }); 
    } 
    self.saveData = function() { 
     var jsonOfLog = JSON.stringify(self.items()); 
     $.ajax({ 
      type: 'POST', 
      dataType: 'text', 
      url: "Home/SaveData", 
      data: "jsonOfLog=" + jsonOfLog, 
      success: function (returnPayload) { 
       console && console.log("request succeeded"); 
      }, 
      error: function (xhr, ajaxOptions, thrownError) { 
       console && console.log("request failed"); 
      }, 

      processData: false, 
      async: false 
     }); 
    } 
} 
ko.applyBindings(new MyViewModel()); 
</script> 

的HomeController:

public ActionResult Index() 
    { 
     return View(); 
    } 
    modelEntities ME = new modelEntities(); 
    [HttpGet] 
    public JsonResult GetData(string date) 
    { 
     DateTime inputdate = DateTime.Parse(date); 

     List<Date> list = ME.Date.Where(key => key.Date1 == inputdate).ToList(); 
     return Json(list, JsonRequestBehavior.AllowGet); 
    } 
    [HttpPost] 
    public string SaveData(string jsonOfLog) 
    { 

     return Convert.ToString(jsonOfLog); 
    } 
+0

'应该传递到保存数据nothing'您可以在此更清晰。 –

+0

如果SaveData应该更新记录,则可能需要使用'Id' – Neps

回答

0
var jsonOfLog = ko.toJSON({ jsonOfLog: self.items }); 

$.ajax({ 
    url:"Home/SaveData", 
    data: jsonOfLog, 
    type: "post", 
    contentType: "application/json", 
    success: function(result) { 
    alert(result) 
    } 
});