将值从控制器发送到MVC中的View [英] Sending a value from the controller to the View in MVC
问题描述
我有一个从我的数据库中检索值的函数。该值必须从控制器发送到我的视图中指定的变量。这可能吗?
这是我的代码:
我的观点编码:
I have a function that retrieves a value from my database. The value must be sent from the controller to the variable specified in my View. Is this possible?
Here is my code :
The coding from my view:
var playerPosition = "";
playerPosition = document.location.href = "Session/GetPlayerPosition?sessionId=@Model.Id&playerId=" + playerId;
来自我的控制器的编码:
The coding from my controller:
public int GetPlayerPosition(int sessionId, string playerId)
{
var sessionRepository = new SessionRepository();
var playerPosition = sessionRepository.GetPlayerPositionByPlayerId(sessionId, int.Parse(playerId.Replace("|", "")));
return playerPosition;
}
我收到我正在寻找的价值,但它在空白页面显示我的价值不在我的javascript变量(playerPosition)
有什么想法吗?
提前致谢。
I receive the value I am looking for but it displays my value on an empty page and not in my javascript variable(playerPosition)
Any ideas?
Thanks in advance.
推荐答案
在ASP.NET MVC中,控制器方法的返回类型必须是ActionResult,并且必须向视图返回一些内容,以便视图可以接收它并使用模型数据。您可以使用ViewBag(一个动态对象)来存储稍后在视图中使用所需的一些值,但如果我是你,我将总是返回一个模型并从具有ActionResult返回类型的方法调用一个视图:
In ASP.NET MVC, the controller method''s return type must be of an ActionResult and you must return something to a view so the view can receive it and use the model data. You can use ViewBag, a dynamic object, to store some values you need to later use in the view but if I were you I would always return a model and call a view from a method that has an ActionResult return type:
public ActionResult Player(int sessionId, int playerId)
{
//Run some Linq statement or call another function, use your variables...
ViewBag.PlayerPosition = GetPlayerPosition(sessionId, playerId);
return View();
}
public int GetPlayerPosition(int sessionId, string playerId)
{
var sessionRepository = new SessionRepository();
var playerPosition = sessionRepository.GetPlayerPositionByPlayerId(sessionId, int.Parse(playerId.Replace("|", "")));
return playerPosition;
}
在您的视图中,如果剃须刀视图和使用,您可以在前面调用带有@字符的ViewBag对象变量:
In your view you can call the ViewBag object with an @ character in front if its a razor view and use the variable:
@ViewBag.PlayerPosition
这篇关于将值从控制器发送到MVC中的View的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!