如何使用cshtml中的Ajax对页面进行部分刷新?
据我所知,Ajax是必需的。在我的场景中,在我的索引页面中,我有一个表,其中每一行都有一个程序(一个批处理文件)和一个Run按钮。在表下面,我有一个用于程序输出的空间。我想让它填充(我很高兴等待程序刚刚完成),而不必刷新页面的其余部分。
下面是代码,但总之,我有一个表数据模型,一个用于选定程序日志/输出的模型。索引页的控制器将两者都创建,并将它们传递给视图模型,视图模型将传递给视图。当单击Run按钮时,控制器中的Index重载方法将处理程序的运行和“获取”输出。它还在VM中填充了适当的模型(可能不理想,我愿意接受改进它的建议)。
重载的方法当前返回一个PartialViewResult,输出/日志记录有它自己的PartialView (我想在其他地方重用它)。这也是为什么它有一个单独的模型。在PartialView中,会命中断点,但它不会出现在浏览器中的页面上。
我在Razor中使用ASP.NET-MVC-4。
视图(Index.cshtml)
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
@model ViewModels.UpdateTestViewModel
@{ ViewBag.Title = "Update Test"; }
@{
<table>
@* Headers *@
<tr>
<td>Programs</td>
</tr>
@* Data *@
<tr>
<td>@Model.ProgramName</td>
<td style="min-width:75px"><input id="btnRun" type="button" value="Run" /></td>
</tr>
</table>
<div id="log">
@Html.Partial("ScriptLog", Model.Log)
</div>
<script>
$("input[type=button]").on("click", function () {
var NAME = ($(this).parent().siblings(":first")).text();
$.post("/UpdateTest/Run", { input: NAME });
});
</script>
}局部视图
@model Models.ScriptLog
@if (Model != null && Model.Log.Any(x => !string.IsNullOrWhiteSpace(x)))
{
<fieldset>
<legend>Log</legend>
@foreach (string entry in Model.Log)
{
<p>@entry</p>
}
</fieldset>
}脚本日志
public IEnumerable<string> Log { get { // returns log } }ViewModel
public class UpdateTestViewModel
{
public string ProgramName { get { return "My Program"; } }
public ScriptLog Log { get { return _log; } }
private readonly ScriptLog _log;
public UpdateTestViewModel(ScriptLog log)
{
_log = log;
}
}控制器
public ActionResult Index()
{
if (SessionFacade.CurrentUpdateTestLog == null)
{
ScriptLog log = new ScriptLog();
SessionFacade.CurrentUpdateTestLog = log; // Store in Session
}
UpdateTestViewModel vm = new UpdateTestViewModel(SessionFacade.CurrentUpdateTestLog);
return View(vm);
}
[ActionName("Run")]
public PartialViewResult Index(string input)
{
ExecuteScript.ExecuteUpdateTestScript(input); // Run batch file
UpdateTestLog(input); // Get log and update in Session
return PartialView("ScriptLog", SessionFacade.CurrentUpdateTestLog);
}发布于 2015-11-23 19:03:10
因为你正在制作一个$.post(),你需要用[HttpPost]来装饰你的/UpdateTest/Run动作。
您也没有定义成功处理程序,因此,当您提出请求时,您永远不会对它做任何事情。
$.post("/UpdateTest/Run", { input: NAME })
.done(function(partialResult) {
$("#log").html(partialResult);
})
.fail(function(jqxhr, status, error) {
console.log(jqXhr, status, error);
});发布于 2015-12-02 10:02:04
经过@Jasen的大力帮助和耐心,我得到了一个可行的解决方案,即扩展现有的Ajax,使其看起来如下:
$("input[type=button]").on("click", function () {
var NAME = ($(this).parent().siblings(":first")).text();
$.post("/UpdateTest/Run", { input: NAME })
.done(function (partialResult) {
$("#log").html(partialResult);
})
});注意,我还在控制器中添加了[HttpPost]属性
https://stackoverflow.com/questions/33876413
复制相似问题