问题描述
我正按照标题所说的那样,在验证后从Controller向视图返回Json消息.
I am trying as the title says to return a Json message from the Controller to the View after it validates.
我已经创建了一个断点,并且我知道代码可以在Controller端运行,并且我的JavaScript现在成功调用了ActionResult.如何在视图"中显示该消息?
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?
有两个按钮,戳入和戳出.如果用户加盖两次,则应该会收到一条消息,与加盖戳相同.除了一些消息和字符串更改之外,我有两个相同的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.
控制器:
[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,
}
});
});
查看:
<input type="text" id="idUser" class="form-control" />
<br />
<input type="submit" value="IN" id="stampInBtn" />
我当然在View中有更多代码; div,标题,正文,标题和脚本.但这可能有点无关紧要.
I have more code inside the View of course; divs, head, body, title and scripts. But it's perhaps a little irrelevant.
我该怎么做才能成功显示这些消息?
What should I do to successfully show those messages?
致谢.
推荐答案
向ajax调用添加成功函数
Add a success function to the ajax call
$.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);
}
});
因此,如果控制器返回
return Json("This is a message");
data
的值将为这是一条消息" .请注意,返回值可以是复杂类型或局部视图
the value of data
will be "This is a message". Note the return value can be a complex type or a partial view
这篇关于从控制器返回Json数据以查看ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!