我正在尝试使用MVC并使用Ajax加载部分视图。我找到了许多不同的例子,但没有一个能够达到我想要的水平,至少没有我找到的例子。
我要做的是创建一个报告页面,顶部将有用户选择(开始/结束日期,付费代码,城市)然后我想用jQuery / Ajax调用控制器,得到数据,填充局部视图,并在用户选择下方显示。
所以我现在所拥有的将使用Javascript抛出错误(我得到的是提示“错误”的警告)但是然后它会将部分页面加载为一个完整的单独页面。我假设AJAX部分失败但随后它转移到控制器POST的服务器端,它只是加载部分视图。我希望在<div id="reportResults">
。
我认为我遇到的第一件事就是我正在使用MVC HTML.Form。那个POST将转到控制器,但我在想,因为我正在尝试使用Ajax,我不会使用MVC表单?
我还有一个ViewModel(TotalHoursReportVM),当最终用户访问页面时用于用户选择,然后是另一个用于获取实际报告记录的ViewModel(TotalHoursReportRecord)。由于我的主View正在寻找TotalHoursReportVM,如果我尝试将TotalHoursReportRecordVM传递给Partial View,显然会给我一个错误。所以,我不知道我应该把这些结合起来,还是我应该合并?
我看了很多文章并尝试了一些事情,以至于我对我正在做的事情感到沮丧和困惑。希望有人可以为我提供一些启示,或者指出我要看一个例子。
这是我的主视图。这只是一个开始/结束数据贴,一对下拉列表和提交按钮。
@model PayrollReports.ViewModels.TotalHoursReportVM
@{
ViewBag.Title = "Total Hours";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@section scripts
{
<script src="@Url.Content("~/Scripts/Views/TotalHoursReport.js")"></script>
}
<h2>Total Hours Report</h2>
<div class="container">
@using (Html.BeginForm("TotalHoursRun", "Report", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary("Report creation was unsuccessful. Please correct the errors and try again.")
<form class="form-horizontal" role="form">
<div class="form-group">
<div class="row voffset3">
<div class="col-md-2 text-left">
<div id="startDatepicker" class="input-group date">
<input class="datepicker form-control" type="text" />
<div class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</div>
</div>
</div>
<div class="col-md-2">
<div id="endDatepicker" class="input-group date">
<input type="text" class="form-control">
<div class="input-group-addon">
<div class="glyphicon glyphicon-calendar"></div>
</div>
</div>
</div>
<div class="col-md-4"></div>
<div class="col-md-4"></div>
</div>
</div>
<div class="form-group">
<div class="row voffset3">
<div class="col-md-4 text-left">
@Html.DropDownListFor(m => m.SelectedPayCode,
new SelectList(Model.PayCodes, "PAY_CODE", "PAY_CODE"),
"-- Select Pay Code --",
new { style = "width:200px;height:30px" })
</div>
<div class="col-md-4">
<div id="templateGroup" style="display:none;">
Available templates<br />
<select id="dropdowntipo">
<option value="Exemplo1">Exemplo1</option>
<option value="Exemplo2">Exemplo2</option>
<option value="Exemplo3">Exemplo3</option>
</select>
</div>
</div>
<div class="col-md-4"></div>
</div>
</div>
<div class="form-group">
<div class="row voffset3">
<div class="col-md-4 text-left">
@Html.DropDownListFor(m => m.SelectedCityCode,
new SelectList(Model.CityCodes, "CityCode", "CityCode"),
"-- Select City --",
new { style = "width:200px;height:30px" })
</div>
<div class="col-md-4"></div>
<div class="col-md-4"></div>
</div>
</div>
<div class="form-group">
<div class="row voffset4">
<div class="col-md-4 text-left">
<button type="submit" id="btnRunReport" class="btn btn-primary">Run Report</button>
<button type="submit" id="btnTemplate" class="btn btn-default">Template</button>
</div>
<div class="col-md-4 text-left">
</div>
<div class="col-md-4"></div>
</div>
</div>
</form>
}
<div id="reportResults">
</div>
</div>
这是我的部分观点:
@model IEnumerable<PayrollReports.ViewModels.TotalHoursReportRecord>
<hr />
<div id="divgrid" style="margin-top: 15px;">
@{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent");
grid.Pager(WebGridPagerModes.NextPrevious);}
<div id="gridContent">
@grid.GetHtml(
tableStyle: "webgrid-table",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
columns: grid.Columns(
grid.Column("EmployeeId", "Employee", style: "id"),
grid.Column("FirstName", "First Name", style: "PName"),
grid.Column("LastName", "Last Name", style: "PName"),
grid.Column("PayCode", "Pay Code", style: "IName"),
grid.Column("PayHours", "Pay Hours", style: "Weight")
))
</div>
</div>
这是我的控制器:
namespace PayrollReports.Controllers
{
public class ReportController : Controller
{
ReportRepository repo = new ReportRepository();
// GET: Report
public ActionResult TotalHours()
{
TotalHoursReportVM model = new TotalHoursReportVM();
return View(model);
}
// POST: Report/TotalHoursRun
[HttpPost]
public ActionResult TotalHoursRun(DateTime? startDate, DateTime? endDate)
{
try
{
if (ModelState.IsValid)
{
var data = repo.GetTotalHoursData();
return PartialView("_TotalHoursGrid", data);
}
return View();
}
catch
{
return View();
}
}
}
这是我的存储库:
public IEnumerable<TotalHoursReportRecord> GetTotalHoursData()
{
List<TotalHoursReportRecord> listHours = new List<TotalHoursReportRecord>();
DateTime startDate = new DateTime(2015, 1, 4);
DateTime endDate = System.DateTime.Today;
using (DataContext db = new DataContext())
{
var payCodes = new string[] { "REG", "AST", "OT" };
var companyCode = new string[] { "SM00", "EA00", "EX00" };
listHours = (from h in db.HOURS
join e in db.SAP_EMPLOYEE on h.EMP_ID equals e.EMP
where companyCode.Contains(e.CO)
&& h.OCCURRENCE_DATE >= startDate
&& h.OCCURRENCE_DATE <= endDate
&& payCodes.Contains(h.PAY_CODE)
select new TotalHoursReportRecord
{
EmployeeId = h.EMP_ID,
FirstName = e.FIRST_NAME,
LastName = e.LAST_NAME,
PayCode = h.PAY_CODE,
PayHours = h.PAY_HOURS,
OccurrenceDate = h.OCCURRENCE_DATE,
CityCode = e.CITY_CODE
}).OrderBy(o => o.LastName)
.ThenBy(o => o.FirstName)
.ThenBy(o => o.OccurrenceDate)
.ThenBy(o => o.PayCode).ToList();
}
return listHours;
}
这是我的ViewModel
namespace PayrollReports.ViewModels
{
public class TotalHoursReportVM
{
public int ReportID { get; set; }
[Required]
public DateTime StartDate { get; set; }
[Required]
public DateTime EndDate { get; set; }
[Required]
public string PayCode { get; set; }
[Required]
public string City { get; set; }
public IEnumerable<APAY_CODES> PayCodes { get; set; }
public int SelectedPayCode { get; set; }
public IEnumerable<CityCodeVM> CityCodes { get; set; }
public int SelectedCityCode { get; set; }
public IEnumerable<TotalHoursReportRecord> TotalHoursReportRecord { get; set; }
public TotalHoursReportVM()
{
var repo = new ReportRepository();
PayCodes = repo.GetPayCodes();
CityCodes = repo.GetCityCodes();
}
}
public class CityCodeVM
{
public string CityCode { get; set; }
}
public class TotalHoursReportRecord
{
public string EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string PayCode { get; set; }
public decimal PayHours { get; set; }
public DateTime OccurrenceDate { get; set; }
public string CityCode { get; set; }
public decimal TotalHours { get; set; }
}
}
这是我的JavaScript:
$(document).ready(function () {
//Datepicker
var startDate = new Date();
startDate.setDate(startDate.getDate() - 7);
var endDate = new Date();
$("#startDatepicker").datepicker("setDate", startDate);
$("#startDatepicker").datepicker("update");
$('#startDatepicker').datepicker().on('changeDate', function (ev) {
$('#startDatepicker').datepicker('hide');
});
$("#endDatepicker").datepicker("setDate", endDate);
$("#endDatepicker").datepicker("update");
$('#endDatepicker').datepicker().on('changeDate', function (ev) {
$('#endDatepicker').datepicker('hide');
});
$('#btnRunReport').click(function () {
/*GET*/
var start = $('#startDate').val();
var end = $('#endDate').val();
$.ajax({
url: '/Report/TotalHoursRun',
contentType: 'application/json; charset=utf-8',
dataType: "html",
type: "GET",
data: { startDate: start, endDate: end },
success: function (result) {
alert(data);
},
error: function (xhr, status)
{
alert(status);
}
});
});
答案 0 :(得分:1)
您可以尝试这样的事情:
变化
<button type="submit" id="btnRunReport" class="btn btn-primary">Run Report</button>
到
<a class="btn btn-primary" href="#" id="btnRunReport" >Run Report</a>
你的ajax调用中的更改
$('#btnRunReport').click(function (e) {
/*GET*/
e.preventDefault();
var start = $('#startDate').val();
var end = $('#endDate').val();
$.ajax({
url: '@Url.Action("TotalHoursRun", "Report")',
dataType: "html",
type: "GET",
data: { startDate: start, endDate: end },
success: function (result) {
$("#reportResults").html(result);
},
error: function (xhr, status)
{
alert(status);
}
});
});
控制器中的
public ActionResult TotalHoursRun(DateTime? startDate, DateTime? endDate)
{
var data = repo.GetTotalHoursData();
return PartialView("_TotalHoursGrid", data);
}