gpt4 book ai didi

javascript - 如果 ActionResult 已完成,如何打印结果

转载 作者:行者123 更新时间:2023-12-03 07:38:54 27 4
gpt4 key购买 nike

调用ActionResult后如何打印结果?

例如,这是我从 View 中进行的调用:

 <a title="Add To Read Later" 
target="_blank"
href="@(Url.Action("Insert", "ReadLater",new {Book_id=Model.Book.Book_id }))">
<small class="fa fa-2x fa-plus"></small>
</a>

这是我的 ReadLaterController 方法:

public ActionResult Insert(int? Book_id)
{
if (User.Identity.IsAuthenticated)
{
var x = User.Identity.GetUserId();
var result = db.Books.Where(p => p.Book_id == Book_id).Single();
if(result.Book_id == Book_id)
{
var IsExists = db.ReadLaters.FirstOrDefault(t => t.Book_Id == result.Book_id && t.User_Id==x);
if (IsExists == null)
{
ReadLater ReadL = new ReadLater()
{
Book_Id = result.Book_id,
User_Id = x.ToString()
};
db.ReadLaters.Add(ReadL);
int state = db.SaveChanges();
if (state == 1)
{

return new JavaScriptResult { Script = "alert('Successfully Added');" };
}
}
else
{

return new JavaScriptResult { Script = "alert('You Added This book Before');" };

}
}
}

return new JavaScriptResult { Script = "alert('Not Added');" };
}

如您所见,如果内容已添加到数据库,我想在调用 Controller 的同一页面中显示一条警报,说明:是否添加或未添加或已添加数据取决于方法结果。 ...

现在,它的工作方式是转到方法 URL 并在没有 JavaScript 效果的情况下打印结果,就像文本一样:

http://localhost:49119/ReadLater/Insert?Book_id=19

该 URL 中的结果是:

alert('You Added This book Before');

最佳答案

这是您可以使用的 AJAX 示例。我把它作为一个按钮..它可以是任何你想要的。

HTML

    <button data-id="@Model.Book.Book_id" class="insertButton fa fa-2x fa-plus">Add to Read Later</button>

Ajax

            $('.insertButton').click(function () {

var myId = $(this).data('id');

$.ajax({
type: "GET",
url: '@Url.Action("Insert","ReadLater")?Book_id=' + myId,
success: function (response) {
alert(response);
},
failure: function (response) {
alert("Failure");
}
});
});

Controller

[HttpGet]
public ActionResult Insert(int? Book_id)
{
if (User.Identity.IsAuthenticated)
{
var x = User.Identity.GetUserId();
var result = db.Books.Where(p => p.Book_id == Book_id).Single();
if (result.Book_id == Book_id)
{
var IsExists = db.ReadLaters.FirstOrDefault(t => t.Book_Id == result.Book_id && t.User_Id == x);
if (IsExists == null)
{
ReadLater ReadL = new ReadLater()
{
Book_Id = result.Book_id,
User_Id = x.ToString()
};
db.ReadLaters.Add(ReadL);
int state = db.SaveChanges();
if (state == 1)
{

return Content("Successfully Added");
}
}
else
{

return Content("You Added This book Before");

}
}
}

return Content("Not Added");
}

关于javascript - 如果 ActionResult 已完成,如何打印结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35493363/

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