gpt4 book ai didi

c# - 在 MVC 中调用方法而不加载 View

转载 作者:行者123 更新时间:2023-11-30 13:39:59 24 4
gpt4 key购买 nike

我目前正在尝试从我的 View 中调用一个方法来更改我的数据库中的一个 bool 值,我唯一不知道的事情是,因为我对 MVC 不是很熟悉,所以每当我调用我的 Controller 方法时,它都会给我一个空白页。我只想调用该方法但留在实际 View 中。

这是我认为的部分代码。

<td><a href="@Url.Action("PutInBin", "Capture", new { captureId = @Model.Files.Captures.ElementAt(i).Capture_Id })", onclick="DeleteCapture(@(i + 1))">Delete</a></td>

这是我 Controller 中的方法

public void PutInBin(int captureId)
{
QueryCaptureToBin queryCaptureToBin = new QueryCaptureToBin();
queryCaptureToBin.Capture_Id = captureId;
client.PlaceCaptureInBin(queryCaptureToBin, userParams);
}

最佳答案

您可以使用 AJAX:

<td>
@Ajax.ActionLink(
"Delete",
"PutInBin",
"Capture",
new {
captureId = Model.Files.Captures.ElementAt(i).Capture_Id
},
new AjaxOptions {
HttpMethod = "POST",
}
)
</td>

并且不要忘记将 jquery.unobtrusive-ajax.js 脚本包含到您的页面中:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

和你的 Controller Action :

[HttpPost]
public ActionResult PutInBin(int captureId)
{
QueryCaptureToBin queryCaptureToBin = new QueryCaptureToBin();
queryCaptureToBin.Capture_Id = captureId;
client.PlaceCaptureInBin(queryCaptureToBin, userParams);
return new EmptyResult();
}

如果您想在删除完成时收到通知:

<td>
@Ajax.ActionLink(
"Delete",
"PutInBin",
"Capture",
new {
captureId = Model.Files.Captures.ElementAt(i).Capture_Id
},
new AjaxOptions {
HttpMethod = "POST",
OnSuccess = "onDeleteSuccess"
}
)
</td>

然后您将拥有 onDeleteSuccess javascript 函数:

var onDeleteSuccess = function(result) {
// normally the result variable will contain the response
// from the server but in this case since we returned an EmptyResult
// don't expect to find anything useful in it.

alert('The capture was successfully deleted');
};

关于c# - 在 MVC 中调用方法而不加载 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9348084/

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