我做錯了什么? 我的方法被呼叫了兩次。 第一次我得到了Id,它的行為是正確的 第二次我得到Null 我不能得到它,正確的解決方法是什么?
我的視圖
<div class="container"/span>>
<div class="row" >
@foreach (var item in Model)
{
<div class="col-md-4"/span>>
<div class="card" style="width: 18rem;" >
<img src="~/Content/not-found-image.jpg" class="card-img-top" alt=" 。
<div class="card-body">
<h5 class="card-title"> @item.Name</h5>
<p class="card-text">一些快速建立在卡標題和構成卡的大部分內容的例子文本。 </p>
<div id="textButton">
<a class="btn btn-primary" data-index="@item.Id" name="link">轉到任何地方</a>。
</div>
</div>
</div>
</div>
}
</div>
</div>
我的控制器
[HttpGet]
public ActionResult ListCoach(int id)
{
if (id != null)
{
var ChoachList = _TraningService.Coach(id)。
return View(ChoachList)。
}
return HttpNotFound()。
Script 我在我的View上使用腳本,使用幫助器 @Section {}
@section scripts {
@*<腳本 src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"/span>></script>*@
<script>
function PassToContoller(data) {
//alert(data);
$.ajax({
型別。"GET",
網址。'/TrainingType/ListCoach'。
資料。{ id: data },
success: function (data) {
console.log(data)。
window.location.href = '/TrainingType/ListCoach'。
return data。
},
error: function () {
$("#loader").fadeOut("慢")。
console.log("error1")。
}
});
}
$(document).ready(function () {
$("a[name=link]").on("click", function () {
var valueOfClickedTag = $(this).data("index") 。
alert("Clicked: " valueOfClickedTag)。
var callFunc = PassToContoller(valueOfClickedTag)
});
$(":button[id=GoToAnywhere3]").on("click", function () {
var valueOfClickedBtn = $(this).data("index") 。
var callFunc = PassToContoller(valueOfClickedBtn)
});
});
</script>
}
如果我使用這個方法: 我不能進入View ListCoach。 我可以在我的視圖上回傳Json嗎?
[]
public JsonResult ListCoach(int id)
{
var ChoachList = _TraningService.Coach(id)。
return Json(ChoachList,JsonRequestBehavior.AllowGet)。
uj5u.com熱心網友回復:
在你的函式PassToContoller中,在ajax success中,你使用window.location.href = '/TrainingType/ListCoach';,所以在你呼叫函式后,它將有兩個請求,一個是ajax,一個是window.location.href。
如果你想在ajax中獲得jsondata,你需要使用dataType: "json",在ajax中。
下面是一個傳遞json資料的演示:
動作:
[HttpGet]
public JsonResult GetJson(int id))
{
return new JsonResult(new TestModel { Id=id,Name="Test") 。)
}
查看:
<button onclick="test()" >
測驗
</button>
@section scripts
{
<腳本>
function test() {
$.ajax({
型別。"GET"。
網址。'GetJson'。
資料。{ id: 1 },
dataType: "json"。
success: function (data) {
console.log(data)。
},
錯誤:函式() {
$("#loader").fadeOut("slow") 。
console.log("error1")。
}
});
}
</script>
}
更新:
你可以嘗試使用一個表單將Id傳遞給動作(不使用<a></a>):
<form asp-action="GetJson"/span> asp-route-id="@item.Id"/span>>
<input type="submit" value="Go to anywhere" />
</form>
行動:
[HttpGet]
public IActionResult GetJson(int id))
{
return View("Index",new List< TestModel> { new TestModel { Id = id, Name = "Test" }. });
}
uj5u.com熱心網友回復:
你的代碼似乎沒有問題,從理論上講,你的動作不應該呼叫兩次,但我想告訴你一些方法,以便抓住問題:
你的代碼似乎沒有問題。
關于你的最后一個問題,我的回答是否定的,你不能使用這種方式來傳遞JSON物件到你的視圖,但你可以通過ViewBag或ViewData來傳遞JSON物件到模型旁邊
。轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/319210.html
標籤:

