我有一个文本字段,用户可以在其中写下短消息(如g +或fb上的状态),在该字段下面我有一个列表,其中需要显示消息。当用户提交该消息时,它存储在数据库中,之后我刷新整个View。这就是我显示该列表的方式:
@foreach (var m in @Model.Messages){
<div>
<p>@m.Author</p>
<p>@m.Text</p>
</div>
}
现在我不想提供更好的用户体验。我不想在View中添加该消息而不刷新。我知道我必须使用JQuery,Ajax等,但我在谷歌搜索过,找不到任何好的教程或ASP MVC / Razor的例子和这个功能。有人可以给我指点吗?
答案 0 :(得分:3)
在谷歌中键入 asp.net mvc ajax jquery 通常会产生足够的结果。但无论如何,这是你能做的。假设您有一个文本字段,用户将在其中键入消息:
@using (Html.BeginForm("AddMessage", "Messages", FormMethod.Post, new { id = "addMessageForm" }))
{
@Html.TextBoxFor(x => x.Author)
@Html.TextAreaFor(x => x.Text)
<button type="submit">Add message</button>
}
你可以通过AJAX化这种形式:
$(function() {
$('addMessageForm').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
$('#messages').append(result);
}
});
return false;
});
});
最后你会有一个控制器动作,它将执行实际的消息添加到数据库:
[HttpPost]
public ActionResult AddMessage(MessageViewModel message)
{
// TODO: add the message to the database
return PartialView("~/Views/Messages/DisplayTemplates/MessageViewModel.cshtml", model);
}
和相应的显示模板(~/Views/Messages/DisplayTemplates/MessageViewModel.cshtml
):
@model MessageViewModel
<div>
@Html.DisplayFor(x => x.Author)
@Html.DisplayFor(x => x.Text)
</div>
并且消息列表将使用显示模板显示,而不是使用循环:
<div id="messages">
@Html.DisplayFor(x => x.Messages)
</div>