[英]Using ASP.NET MVC and jQuery to render partial view/submit a form without page refresh
I'm new to ASP.NET MVC and jQuery, so I thought I'd share how I implemented loading of partial views and submitting forms in a way that doesn't require for the entire page to be refreshed. 我是ASP.NET MVC和jQuery的新手,所以我想分享一下如何实现部分视图的加载和提交表单的方式,而无需刷新整个页面。 I hope to get some critique from the experts if there's a better way to do this :) 如果有更好的方法,我希望得到专家的批评:)
All the magic is done by 3 javascript functions which I bind to various events, like button click, jQueryUI tab select, etc. 所有的魔力都是由3个javascript函数完成的,这些函数可以绑定到各种事件,例如按钮单击,jQueryUI选项卡选择等。
Firstly, this is how I get a partial view: 首先,这是我得到部分视图的方式:
function showAjaxMessage(targetDiv, ajaxMessage) {
var ajaxLoader = "<img src='Content/loader.gif' alt=''>";
$(targetDiv).html("<p>" + ajaxLoader + " " + ajaxMessage+"</p>");
}
function getPartialView(actionUrl, targetDiv, ajaxMessage, callback) {
showAjaxMessage(targetDiv, ajaxMessage);
$.get(actionUrl, null, function(result) {
$(targetDiv).html(result);
callback();
});
}
Usage: 用法:
getPartialView("MyController/MyAction", "#myDiv", "Loading...", function() { alert('Loaded!'); });
This will set whatever the action returned (PartialView) as the content of myDiv and then invoke the callback function (in this case, it will just pop up an alert) with a nice "Loading..." message displayed in the div while we wait for the response. 这会将返回的任何操作(PartialView)设置为myDiv的内容,然后调用回调函数(在这种情况下,它将弹出一个警报),同时在div中显示一条漂亮的“ Loading ...”消息,同时我们等待回应。
Secondly, submitting a form: 其次,提交表格:
function submitForm(actionUrl, targetDiv, ajaxMessage, form, callback) {
var data = $(form).serialize();
showAjaxMessage(targetDiv, ajaxMessage);
$.post(
actionUrl,
data,
function(data) {
$(targetDiv).html(data);
callback();
}
);
}
Usage: 用法:
submitForm("MyController/MyAction", "#myDiv", "Submitting...", "#myForm", function() { alert('Submitted!'); });
Once again, this invokes a controller action, but this time it does a POST with the given form's data (<form id="myForm">) serialized as "input1=value1&input2=value2&...&inputn=valuen", allowing the action to do something with the user input, like so: 再次,这将调用控制器操作,但是这一次它使用序列化为“ input1 = value1&input2 = value2&...&inputn = valuen”的给定表单数据(<form id =“ myForm”>)进行POST,从而允许该操作使用用户输入来执行某些操作,例如:
public ActionResult MyAction(FormCollection form)
{
// eg. TryUpdateModel<MyActionViewModel>(this.myActionViewModel);
// or
// do something with form["input1"] ...
return PartialView("MyPartialView", this.myActionViewModel);
}
The HTML returned is once again rendered into myDiv and a callback function is invoked. 返回的HTML再次呈现到myDiv中,并调用了回调函数。
I haven't added any validation as yet, but the basics work quite nicely, but if there is a better way, please share :) 我还没有添加任何验证,但是基础工作正常,但是如果有更好的方法,请分享:)
I'd just use jQuery.taconite : 我只用jQuery.taconite :
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.