我有一个根据用户输入动态更新的 View - 这是它的工作原理:
- View 使用来自填充了部分 View 的 Controller 的初始数据呈现
- 当单击某些内容时,我使用从 Controller 的 ActionResult 中检索部分 View 并使用 jQuery 替换现有数据
- 我需要一个来自 Controller 的主视图字符串,所以我再次调用 Controller 并检索一个字符串。
我想知道是否有一种方法可以通过局部 View 获取我需要的字符串,而不是进行单独的 Controller 调用。
初始数据:
<!-- This needs to change when the partial is replaced, but it's heavier html
and I don't want to include it in the partial to minimize server calls/data -->
<div class="Location"> </div>
<div class="myContainingDiv">
<!-- This content gets updated -->
@Html.Partial("_MyPartial");
</div>
局部 View :
<div class="something">Model.something</div>
Controller 方法(部分 View ):
[HttpGet]
public ActionResult _MyPartial(string param1)
{
MyModel model = new MyModel();
// This is dynamic and what I need to get in my main view from the partial view
model.something = "Hi";
return PartialView(model);
}
Controller 方法(返回所需的字符串):
public string GetHiString(string param1)
{
return "Hi";
}
JavaScript(更新局部 View ):
$.post('/Home/_MyPartial', { 'param1': 'Hi' }, function (result) {
$('.something').replaceWith(result);
getOtherThing('Hi');
});
JavaScript(getOtherThing):
$.post('/Home/_GetHiString', { 'param1': 'Hi' }, function (result) {
$('.Location').replaceWith(result);
});
好的,我想这就是一切。
基本上每次调用我只想点击一次 Controller 。在局部 View 中包含 div 不是一个理想的选择。
我第二次从我的主视图中点击 Controller 以获取可以从第一个方法中的对象轻松创建并向下发送到部分 View 的数据。
所以,除了包括<div class="Location">
在我的局部 View 中,有没有一种方法可以将我需要的额外信息发送到局部 View 并从我的主视图中动态检索(通过 JavaScript)。或者当我调用 _MyPartial
时有没有办法返回额外的数据?来 self 的 JavaScript?
这真的是我想做的最后一个简化,非常感谢您的帮助!
最佳答案
您可以修改分部 View _MyPartial
及其模型以包含隐藏在其中的内容,您可以使用 jQuery 提取这些内容:
局部 View
<div class="something">Model.something
<input class="somethingElse" type="hidden" value="@(Model.somethingElse)" />
</div>
Controller 方法(部分 View ):
[HttpGet]
public ActionResult _MyPartial(string param1)
{
MyModel model = new MyModel();
// This is dynamic and what I need to get in my main view from the partial view
model.something = "Hi";
model.somethingElse = GetHiString(param1);
return PartialView(model);
}
JavaScript(更新局部 View )
$.post('/Home/_MyPartial', { 'param1': 'Hi' }, function (result) {
$('.something').replaceWith(result);
$('.Location').html($('.somethingElse').val());
});
关于c# - 通过 jQuery 从发布请求的部分 View 中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9930790/