javascript 从控制器返回 Json 数据以查看 ASP.NET MVC
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25972656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning Json Data From Controller to View ASP.NET MVC
提问by Qvadriologic
I am trying as the title says to return a Json message from the Controller to the View after it validates.
正如标题所说,我正在尝试在验证后将 Json 消息从控制器返回到视图。
I have made a breakpoint, and I know that the code works from Controller side, and that my JavaScript calls with success the ActionResult now. How do I display that message in the View?
我已经创建了一个断点,并且我知道代码在控制器端工作,并且我的 JavaScript 现在成功调用了 ActionResult。如何在视图中显示该消息?
There are two buttons, stamp in and stamp out. If the user stamps in twice, it should get a message, same with stamp out. I have two ActionResults who are indentical except some message and string changes.
有两个按钮,戳入和戳出。如果用户戳两次,它应该得到一条消息,与戳出相同。我有两个 ActionResults,除了一些消息和字符串更改外,它们是相同的。
Controller:
控制器:
[HttpPost]
public ActionResult CreateStamp(Stamping stampingmodel)
{
var validateMsg = "";
stampingmodel.Timestamp = DateTime.Now;
stampingmodel.StampingType = "in";
if (stampingmodel.User == null || ModelState.IsValid)
{
var idValidated = db.Users.Find(model.UserId);
if (idValidated != null)
{
var stamp =
db.Stampings.Where(s => s.UserId == stampingmodel.UserId)
.OrderByDescending(s => s.Timestamp)
.FirstOrDefault();
if (stamp.StampingType == stampingmodel.StampingType)
{
if (stampingmodel.StampingType == "in")
{
validateMsg = "Stamped Twice In A Row!";
}
}
else
{
if (stampingmodel.StampingType == "in")
{
validateMsg = "Stamped In, Welcome.";
}
}
}
db.Stampings.Add(stampingmodel);
db.SaveChanges();
}
return Json(new {Message = validateMsg });
JavaScript:
JavaScript:
$(document).ready(function () {
$("#stampInBtn").click(function () {
var userId = $("#userId").val();
$.ajax({
url: "ComeAndGo/CreateStamp",
type: "POST",
dataType: "json",
data: {
userId: userId,
}
});
});
View:
看法:
<input type="text" id="idUser" class="form-control" />
<br />
<input type="submit" value="IN" id="stampInBtn" />
I have more code inside the View of course; divs, head, body, title and scripts. But it's perhaps a little irrelevant.
当然,我在 View 中有更多代码;div、头部、正文、标题和脚本。但这可能有点无关紧要。
What should I do to successfully show those messages?
我应该怎么做才能成功显示这些消息?
Regards.
问候。
采纳答案by Qvadriologic
Add a success function to the ajax call
给ajax调用添加成功函数
$.ajax({
url: "ComeAndGo/CreateStamp",
type: "POST",
dataType: "json",
data: { userId: userId },
success: function(data) {
// data contains the value returned by the server
console.log(data);
}
});
So if the controller returns
所以如果控制器返回
return Json("This is a message");
the value of data
will be "This is a message". Note the return value can be a complex type or a partial view
的值data
将是“这是一个消息”。注意返回值可以是复杂类型或部分视图
回答by Giannis Paraskevopoulos
You are getting the value of $("#userId")
, but your input has an id of idUser
.
您正在获取 的值$("#userId")
,但您的输入的 id 为idUser
。
Try making your input:
尝试输入:
<input type="text" id="userId" class="form-control" />
Also it would be a good idea to provide your Stamping
model structure as it seems that you only pass the user id in your post and nothing else.
此外,提供您的Stamping
模型结构也是一个好主意,因为您似乎只在帖子中传递用户 ID 而没有其他任何内容。
回答by Sujit Patil
Change your javascript code as following:
更改您的 javascript 代码如下:
$(document).ready(function () {
$("#stampInBtn").click(function () {
var userId = $("#userId").val();
$.ajax({
url: "ComeAndGo/CreateStamp",
type: "POST",
dataType: "json",
data: {
userId: userId,
},
success: function(data) {
var objData= jQuery.parseJSON(data);
alert(objData.Message );
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
});