使用JSON保留数据

时间:2009-12-31 18:46:08

标签: c# javascript asp.net-mvc json

我正在尝试使用JSON更新数据库中的记录而不进行回发,而我在实现它时遇到了麻烦。这是我第一次这样做,所以我希望被指向正确的方向。

(解释,与我的问题无关:我正在显示一个可以使用jquery插件排序的项目列表。项目的文本也可以编辑。当人们点击提交时我希望他们的记录更新。功能将与this非常相似。)。

这个javascript函数创建了一个对象数组。我之后不知道该怎么办。它由按钮的onClick事件调用。

 function SaveLinks() {
     var list = document.getElementById('sortable1');
     var links = [];

     for (var i = 0; i < list.childNodes.length; i++) {
         var link = {};
         link.id = list.childNodes[i].childNodes[0].innerText;
         link.title = list.childNodes[i].childNodes[1].innerText;
         link.description = list.childNodes[i].childNodes[2].innerText;
         link.url = list.childNodes[i].childNodes[3].innerText;

         links.push(link);
     }

     //This is where I don't know what to do with my array.         
 }

我试图让它调用一个将信息保存到数据库的更新方法。这是我的代码隐藏函数,将从javascript中调用。

    public void SaveList(object o )
    {
        //cast and process, I assume
    }

感谢任何帮助!

3 个答案:

答案 0 :(得分:2)

我最近这样做了。我正在使用MVC虽然它不应该太不同。

这并不重要,但我发现在客户端和服务器端的C#中创建JS的合同很有帮助,这样您就可以确定您的界面了​​。

这里有一些示例Javascript(带有jQuery库):

var item = new Item();
item.id = 1;
item.name = 2;
$.post("Item/Save", $.toJSON(item), function(data, testStatus) {
  /*User can be notified that the item was saved successfully*/
  window.location.reload();
}, "text");

在上面的例子中,我希望从服务器返回文本,但这可以是XML,HTML或更多JSON。

服务器代码是这样的:

public ActionResult Save()
{
    string json = Request.Form[0];

    var serializer = new DataContractJsonSerializer(typeof(JsonItem));
    var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(json));
    JsonItem item = (JsonItem)serializer.ReadObject(memoryStream);
    memoryStream.Close();

    SaveItem(item);

    return Content("success");
}

希望这是有道理的。

答案 1 :(得分:0)

您不使用CodeBehind,使用新操作。

您的操作将采用可以从您发布的数据(在您的情况下,是JavaScript对象,而不是JSON)中实现的参数。所以你需要一个类似的东西:

public class Link
{
    public int? Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Url { get; set; }
}

注意可以为空的int。如果编辑模型中包含不可为空的类型,则如果用户未提交该属性的值,则绑定将失败。使用可空类型允许您检测控制器中的null并为用户提供信息性消息,而不是仅为整个模型返回null。

现在添加一个动作:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DoStuff(IEnumerable<Link> saveList)
{
    Repository.SaveLinks(saveList);
    return Json(true);
}

将您的JS对象更改为MVC的DefaultModelBinder将理解的表单:

 var links = {};
 for (var i = 0; i < list.childNodes.length; i++) {
     links["id[" + i + "]"] = list.childNodes[i].childNodes[0].innerText;
     links["title[" + i + "]"] = list.childNodes[i].childNodes[1].innerText;
     links["description[" + i + "]"] = list.childNodes[i].childNodes[2].innerText;
     links["url[" + i + "]"] = list.childNodes[i].childNodes[3].innerText;
 }

最后,在你的JS中调用动作:

//This is where I don't know what to do with my array.  Now you do!
// presumes jQuery -- this is much easier with jQuery
$.post("/path/to/DoStuff", links, function() { 
    // success!
    },
    'json');

答案 2 :(得分:-1)

不幸的是,JavaScript没有用于将结构序列化为JSON的内置函数。因此,如果您想在Ajax查询中发布一些JSON,您必须自己使用字符串或使用第三方序列化程序。 (例如,jQuery有一个a plugin或两个。)

也就是说,您通常不需要将JSON发送到HTTP服务器来处理它。您可以简单地使用Ajax POST请求并以常规方式(application/x-www-form-urlencoded)对表单进行编码。

您无法以这种方式发送嵌套数组等结构化数据,但您可以通过计数器命名links结构中的字段。 (links.id_1links.id_2等。)

如果你这样做,那么像jQuery这样的东西就像

一样简单
jQuery.post( '/foo/yourapp', links, function() { alert 'posted stuff' } );

然后你必须重新构建服务器端的数据。