如何通过jQuery ajax更新ASP.NET MVC ViewData? [英] How can I update a ASP.NET MVC ViewData via jQuery ajax?

查看:150
本文介绍了如何通过jQuery ajax更新ASP.NET MVC ViewData?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面高度依赖于我在ViewData中传递的IList(在ActionResult"MyEvents"中).像这样: ViewData ["events"] = listOfEvents; 最后,我只是返回View();

在我的视图中,我使用此ViewData ["events"]并在其中进行foreach操作,以便遍历其内容.

但是,必须动态填充此ViewData.因此,当我单击某天(我正在使用jQuery DatePicker)时,这一天将作为"MyEvents"的参数发送,这一天对于将填充ViewData ["events"]的listOfEvents非常重要. /p>

但是,我得到的结果是包含我的foreach的div在其中创建了另一个整页!我尝试做 $(#myDiv").html(contentFromMyEvents),这就是发生的情况.

仅出于测试目的,我还尝试过执行 $(#myDiv").text(contentFromMyEvents),整个html代码及其所有标签和页面上的所有其他内容都显示在其中div!那是一页内的一页!

所以,我认为这是因为我要返回" return View(); ",当然,它将再次呈现我的整个View.

因此,我如何只传递ViewData ["events"]并在页面上对其进行更新?

谢谢!

解决方案

查看jQuery中的load函数( http://docs.jquery.com/Ajax/load ).加载后调用您的控制器,然后将结果注入到html文档中.

$("myDiv").load("/Controller/Action");

您的ViewData将在服务器端进行解析.而不是返回View(),而是返回指向用户控件的PartialView().产生的只是一个HTML片段.

I have a page that highly depends on a IList (in ActionResult "MyEvents") that I pass in ViewData. Something like that: ViewData["events"] = listOfEvents; and in the end, I just return View();

And in my View, I take this ViewData["events"] and do a foreach in it so I can iterate through its contents.

But, this ViewData must be dynamically filled. So, when I click on a day (I'm using jQuery DatePicker), this day is sent as an argument to "MyEvents" and this day will be very important to my listOfEvents that will fill my ViewData["events"].

But, the result I'm getting is that the div that contains my foreach creates another whole page inside it!! I've tried to do $("#myDiv").html(contentFromMyEvents) and this was what happened.

Just for testing, I've tried also to do $("#myDiv").text(contentFromMyEvents) and the whole html code with all its tags and everyting else from my page appeared inside the div! It was a page inside a page!!

So, I think that is happening because I'm returning "return View();" and of course it will render my whole View again.

So, how can I pass just the ViewData["events"] and update it on my page??

Thanks!!

解决方案

Look to the load function in jQuery(http://docs.jquery.com/Ajax/load). Call your controller with load and then inject the result into your html document.

$("myDiv").load("/Controller/Action");

Your ViewData will be parsed on the server side. Instead of returning View(), return a PartialView() pointing to a user control. What comes out the is just a HTML fragment.

这篇关于如何通过jQuery ajax更新ASP.NET MVC ViewData?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆