【发布时间】:2017-06-26 14:41:22
【问题描述】:
我是 ASP.NET 新手,在向主视图添加内容时遇到问题。在 HtmlBeginform 中,我通过单击按钮上传文件,文件加载后,我需要在主视图下显示部分视图,我不知道如何正确调用 ajax 脚本。
我的主要观点:
@using prvniAplikace.Models;
@using Chart.Mvc.ComplexChart;
@using Chart.Mvc.Extensions;
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm("LoadFile", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<div class="form-group" align="left">
<label for="exampleInputFile">Load File</label>
<input type="file" accept=".tcx" class="form-control-file" name="exampleInputFile" id="exampleInputFile" aria-describedby="fileHelp">
</div>
<div class="form-group" align="left">
<button class="btn btn-primary" type="submit" id="add" name="add" value="Add">Display</button>
</div>
}
@section Scripts {
<script type="text/javascript">
$("#add").on('click', function () {
$.ajax({
async: false,
url: '/Home/getContent'
}).success(function (partialView) {
$('#getContent').append(partialView);
});
});
</script>
}
我要添加到主视图的视图:
@{
ViewBag.Title = "getContent";
Layout = null;
}
<h2>Obsah</h2>
<p>Odstavec</p>
<p>@DateTime.Now.ToString()</p>
控制器:
namespace prvniAplikace.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
public ActionResult getContent()
{
return PartialView("~/Views/Home/AjaxRequest.cshtml");
}
[HttpPost]
public ActionResult LoadFile(HttpPostedFileBase exampleInputFile)
{
if (exampleInputFile.ContentLength > 0)
{
var fileName = Path.GetFileName(exampleInputFile.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
exampleInputFile.SaveAs(path);
string xmlFile = Server.MapPath(fileName);
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNodeList nodes = doc.GetElementsByTagName("HeartRateBpm");
XmlNodeList nodes2 = doc.GetElementsByTagName("Time");
}
return RedirectToAction("Index");
}
}
}
【问题讨论】:
-
目前您的 ajax 调用是通过单击添加按钮连接的,它不会执行 ajax 文件上传,而是正常的表单提交,之后您将执行新的 GET 到索引页面(因为 RedirectToAction 方法调用)。您想何时显示部分视图内容?成功上传(不是ajax文件上传)后加载索引页面时?
-
我通过普通提交表单上传文件,然后我需要在当前视图下添加一些进一步的内容。上传成功后索引页面不会加载,它只是显示一条消息。你建议做不同的事情吗?
-
由于是普通的表单提交,当你点击提交按钮时,表单将被提交,服务器返回302响应(对于索引页面的新GET请求)。你什么时候真正想在这个流程中显示你的局部视图结果?
-
局部视图应显示在索引视图的正下方。
-
什么时候?在您的普通表单提交后索引视图被(重新)加载之后?
标签: asp.net ajax asp.net-mvc