gpt4 book ai didi

jquery - MVC Ajax 部分 View - 根据返回的 View 加载到不同的 div

转载 作者:行者123 更新时间:2023-11-28 02:49:36 31 4
gpt4 key购买 nike

有没有办法根据从 MVC 操作返回哪个 View 来设置局部 View 加载到哪个 div?例如,MVC Controller 操作可以根据某些逻辑返回两个 View ( View A 或 View B)之一。如果返回“ View A”,则在 Ajax 调用的完成函数中将其加载到“div A”中,但如果返回“ View B”,则将其加载到“div B”中。

public ActionResult SomeActionMethod()
{
if (someCondition == true) {
return PartialView("ViewA", new SomeModel());
}
else {
return PartialView("ViewB", new AnotherModel());
}
}
.done(function(data) {
if (isViewA === true) { // How do I determine which view it is?
$('#div-a').html(data);
} else {
$('#div-b').html(data);
}
})

是否有已知/可接受的方法来执行此操作(如何确定它是 View A 还是 View B)?我想到了两种方法来做到这一点,但都看起来有点老套。如果没有普遍接受/批准的方法来做到这一点,那么以下想法是否可行......

想法 1:

在返回的 html 中搜索仅在该 View 中找到的唯一元素或隐藏输入值。这并不像最初听起来那么容易,因为返回的数据不仅仅是简单的 html,而是某种嵌套的字符串/对象(不太确定)。对于顶级元素,需要使用 jQuery 'filter' 方法:

$(data).filter('#unique-element');

否则应使用“查找”方法。

想法 2:

在 Controller 操作中,对于返回的 View 之一( View A),将 Response.StatusCode 设置为 200 范围内尚未使用的自定义值(不是 200-208、226)。然后在 ajax done 函数中指定所有 3 个参数并检查第三个参数状态属性以与您在 Controller 操作中设置的响应状态进行比较。

if (someCondition == true) {
Response.StatusCode = 299;
return PartialView("ViewA", new SomeModel());
}
else {
return PartialView("ViewB", new AnotherModel());
}
.done(function(data, textStatus, jqXHR) {
if (jqXHR.status === 299) {
// It’s View A so load it into div A
}
else {
// It’s View B so load it into div B
}
})

这就像一个魅力,但看起来比想法 1 更 hacky。

最佳答案

我建议分别加载每个 div 的内容。例如:

Javascript

$('div-a').html(contentforA);
$('div-b').html(contentforB);

Controller

public ActionResult ContentA()
{
if (someCondition)
{
return PartialView("ViewA", new SomeModel());
}
return new EmptyResult();
}

public ActionResult ContentB()
{
if (!someCondition)
{
return PartialView("ViewB", new AnotherModel());
}
return new EmptyResult();
}

关于jquery - MVC Ajax 部分 View - 根据返回的 View 加载到不同的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39907572/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com