does not contain public definition for get enumerator - model-view-controller

my view statement shows error that " for each statement cannot operate on variables of type public definition for 'get enumerator' "
I defined all objects in model and view models. still i get this error. any solution for this?
MY VIEW:
#using Edi.ViewModel
#model viewmodel
#{
<link rel="stylesheet" type="text/css" href="~/Content/style.css" />
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form id="form1" name="zoo">
<div class="med">
<pre>
<fieldset id="field1">
<legend>Bill Date Range</legend>
<input type="checkbox">After <input type="date" /> <input type="checkbox">Before <input type="date" />
</fieldset>
<fieldset id="field2">
<legend>Options</legend>
<label>Facility</label> #Html.DropDownListFor(Model => Model.Facility, Model.Facility, "Select Facility", new { style = "width:200px; height :30px" })
<label>Ins Queue</label> #Html.DropDownListFor(Model => Model.InsQueue, Model.InsQueue, "Select InsQueue", new { style = "width:200px; height:30px" })
Claim type <select style="width: 100px; height:30px"><option value="ALL">All</option><option value="NEW">New</option><option value="RESUBMIT">Resubmit</option></select>
</fieldset>
<pre>
<label>No of Bills Selected </label><input type="text" size="1" /> <label> EDI send To </label> #Html.DropDownListFor(Model => Model.EdiSendTo, Model.EdiSendTo, "Select Edi", new { style = "width:200px; height :30px" }) <button type="button" onclick="">Select All</button> <button type="reset" onclick="">Refresh</button> <button type="button" onclick="">Clear All</button> <button type="button" onclick="">Edit Bill</button>
</pre>
<table id="myTable">
<tr class="hd">
<th>visit</th>
<th>billno</th>
<th>patient</th>
<th>providername</th>
<th>insname</th>
<th>payby</th>
<th>inscode</th>
<th>user</th>
<th>claimtype</th>
</tr>
-------------------#foreach (var items in Model)------------------------------
{
<tr onclick="javascript:showRow1(this);">
<td>#items.visit</td>
<td>#items.billno</td>
<td>#items.Patient</td>
<td>#items.ProviderName</td>
<td>#items.InsName</td>
<td>#items.PayBy</td>
<td>#items.InsCode</td>
<td>#items.User</td>
<td>#items.ClaimType</td>
</tr>
}
</table>
</div>
</form>
</body>
</html>
MY CONTROLLER:
namespace Edi.Controllers
{
public class HomeController :Controller
{
// GET: Home
public ActionResult Index()
{
mbill mt = new mbill();
billing db = new billing();
viewmodel vm = new viewmodel();
vm.Facility = db.Add1();
vm.EdiSendTo = db.Add2();
vm.InsQueue = db.Add3();
List<mbill> itemlist = new List<mbill>();
itemlist = db.Index();
return View("Index",vm);
}
}
}
MY MODEL:
public List<mbill> Index()
{
List<mbill> itemList = new List<mbill>();
connection();
SqlCommand cmd = new SqlCommand("procGetEDIBills", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sd.Fill(dt);
mbill item = new mbill();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
mbill io = new mbill();
while (sdr.Read())
{
io = new mbill();
io.visit = sdr["VisitDate"].ToString();
io.billno = sdr["Billno"].ToString();
io.Patient = sdr["PatientName"].ToString();
io.ProviderName = sdr["ProviderName"].ToString();
io.InsName = sdr["InsuranceName"].ToString();
io.PayBy = sdr["BillPayBy"].ToString();
io.InsCode = sdr["InsuranceId"].ToString();
io.User = sdr["QueueByUser"].ToString();
io.ClaimType = sdr["ClaimType"].ToString();
itemList.Add(io);
}
}
con.Close();
return itemList;
}
}
if i delete #using Edi.ViewModel, #model viewmodel, on view then foreach error disappears and dropdownlistfor shows does not contain definition for dropdownlistfor error.

Related

Unable to get updated Checkboxes from uploaded Excel file in asp.net core 3.1 mvc

As soon as the Excel file is uploaded and clicked on Submit button, the data in the Excel file will be populated as shown in the below screenshot. Some checkboxes will be selected while some others are not, based on the conditions written in the program. Till here everything is working fine.
End user selects/un-selects checkboxes, and clicks on Process Hold Reasons button. Now, I want updated model with modified checkboxes values. I'm not even understanding how and where to write the code to achieve this. Tried number of ways, but unable to succeed.
Can someone please suggest me on this!
Below is the code in Index.cshtml page.
#model SupportTool.Models.ViewModels.EligibilityIssuesViewModel
#{
ViewData["Title"] = "Eligiblity Issues";
}
<style>
.Success {
font-weight: bold;
color: green;
font-size: 15px;
}
.Error {
font-weight: bold;
color: red;
font-size: 15px;
}
td {
height: 20px;
}
</style>
<br />
<br />
<div>
<span class="Success">#ViewBag.Success</span>
<span class="Error">#ViewBag.Error</span>
</div>
<form asp-controller="EligibilityIssues" asp-action="Index" method="post" class="form-horizontal" role="form" enctype="multipart/form-data">
<div class="form-group">
<div class="row">
<div class="alert-danger" asp-validation-summary="ModelOnly"></div>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<p>Upload Excel file:</p>
<div class="custom-file">
<input asp-for="ExportedExcelFile" class="form-control custom-file-input" />
<label class="custom-file-label">Choose file...</label>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="Submit" class="btn-success" />
</div>
</div>
</div>
#section Scripts {
<script>
$(function () {
$('.custom-file-input').on('change', function () {
var fileName = $(this).val().split('\\').pop();
$(this).next('.custom-file-label').html(fileName);
});
});
</script>
}
#if (Model != null && Model.HoldReasons != null)
{
<h1>Eligibility issues should be shown here</h1>
<table>
<thead>
<tr>
<th> </th>
<th>Hold Reasons</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.HoldReasons.Count; i++)
{
<tr>
<td>
#Html.CheckBox("holdReason[" + i + "].HoldReasonShouldBeChecked", Model.HoldReasons[i].HoldReasonShouldBeChecked)
#if (!Model.HoldReasons[i].HoldReasonShouldBeChecked)
{
<span style="border: 1px solid red">
(#Model.HoldReasons[i].StateName)#Model.HoldReasons[i].HoldReason
</span>
}
else
{
<span>(#Model.HoldReasons[i].StateName)#Model.HoldReasons[i].HoldReason</span>
}
#Html.Hidden("holdReason[" + i + "].WorkOrderId", Model.HoldReasons[i].WorkOrderId)
</td>
</tr>
}
</tbody>
</table>
<input type="submit" asp-action="ProcessHoldReasons" value="Process Hold Reasons" class="btn btn-primary" />
}
</form>
Below is the Code in HomeController
namespace SupportTool.Controllers
{
public class EligibilityIssuesController : Controller
{
private readonly IEligibilityIssuesBLL _bll;
private readonly IWebHostEnvironment _hostEnvironment;
public EligibilityIssuesController(IEligibilityIssuesBLL bll, IWebHostEnvironment hostEnvironment)
{
_bll = bll ?? throw new ArgumentNullException(nameof(bll));
_hostEnvironment = hostEnvironment ?? throw new ArgumentNullException(nameof(hostEnvironment));
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(EligibilityIssuesViewModel model)
{
try
{
if (ModelState.IsValid)
{
if (model.ExportedExcelFile != null)
{
var folder = Path.Combine(_hostEnvironment.WebRootPath, "uploaded_excel_files");
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
var incomingFileName = model.ExportedExcelFile.FileName;
model.UploadedExcelFileName = Path.Combine(folder, incomingFileName);
using (var fileStream = new FileStream(model.UploadedExcelFileName, FileMode.Create))
{
model.ExportedExcelFile.CopyTo(fileStream);
}
model.HoldReasons = _bll.GetHoldReasons(model);
}
return View(model);
}
return View(model);
}
catch (Exception ex)
{
ViewBag.Error = new HtmlString(#"Unexpected error occurred. Below is the message for your verification:<br />"
+ ex.Message);
return View(model);
}
}
}
}

Handling Razor Dropdowns for auto load values

I have two dropdowns in the view but one relies on the selected value from the other. But how could i load values into the second dropdown after selecting a value from the other? The second dropdown should load values basing on the id selected from the other dropdown.
<div class="form-group">
<label asp-for="BankId" class="control-label col-xs-2"></label>
<div class="col-xs-4">
<select class="form-control" asp-for="BankId" asp-items=#bank>
<option>--- select bank ---</option></select>
</div>
</div>
<div class="form-group">
<label asp-for="BankBranchId" class="control-label col-xs-2"></label>
<div class="col-xs-4">
<select class="form-control" asp-for="BankBranchId" asp-items=#bankbranches>
<option>--- select bank branch ---</option></select>
</div>
</div>
BankBranch should fill values basing on the bank selected from up
Below is example for bank and branches.
you can try out something
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.DropDownListFor(m => m.bank, Model.bank, "Please select", new { onchange = "document.forms[0].submit();" })
<br/>
<br/>
#Html.DropDownListFor(m => m.branches, Model.branches, "Please select", new { disabled = "disabled" })
<br/>
<br/>
<input type="submit" value="Submit"/>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
if ($("#bank option").length > 1) {
$("#bank").removeAttr("disabled");
}
if ($("#branches option").length > 1) {
$("#branches").removeAttr("disabled");
}
if ($("#bank").val() != "" && $("#branches").val() != "") {
var message = "Bank: " + $("#CountryId option:selected").text();
message += "\nbranck: " + $("#StateId option:selected").text();
alert(message);
}
});
</script>
</body>
</html>
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
// populate bank values
foreach (var bankent in entities.bank)
{
model.bank.Add(new SelectListItem { Text = bankent.bank, Value = bankent.id.ToString() });
}
return View(model);
}
[HttpPost]
public ActionResult Index(int? bank)
{
// populate bank values
foreach (var bankent in entities.bank)
{
model.bank.Add(new SelectListItem { Text = bankent.bank, Value = bankent.id.ToString() });
}
if (bank.HasValue)
{
//populate branches based on bank id
foreach (var state in branches)
{
model.branches.Add(new SelectListItem { Text = state.branches, Value = state.StateId.ToString() });
}
}
return View(model);
}
}
for more detail check out Populate one DropDownList based on another DropDownList selected value in ASP.Net MVC

i want to convert my gridview table into pdf

**when i tried to convert my grid-view data into PDF i got null reference exception grid-view header row but data is available in grid view.please help me to solve this error. i am using asp.net web API in this.. and i tried to on another grid-view to bind data..it shows same error null reference exception but when i tried on direct button click it works fine..only it shows error when i tried on using web API..please help me to solve this
i have attached my programming below data load and bind
public void GetData()
{
string conn = ConfigurationManager.ConnectionStrings["con"].ToString();
SqlConnection con = new SqlConnection(conn);
con.Open();
SqlCommand cmd = new SqlCommand("select * from api", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "api");
//DataTable dta = new DataTable();
//dta = ds.Tables["api"];
//da.Fill(dta);
GridView2.DataSource = ds;
GridView2.DataBind();
}
convert to pdf
public string Button3_Click()
{
PdfPTable pdfTable = new PdfPTable(GridView2.HeaderRow.Cells.Count);
foreach (TableCell headercell in GridView2.HeaderRow.Cells)
{
iTextSharp.text.Font font = new iTextSharp.text.Font();
font.Color = new Basecolor(GridView2.HeaderRow.ForeColor);
PdfPCell pdfcell = new PdfPCell(new Phrase(headercell.Text, font));
pdfcell.BackgroundColor = new Basecolor(GridView2.HeaderStyle.BackColor);
pdfTable.AddCell(pdfcell);
}
foreach (GridViewRow gridviewrow in GridView2.Rows)
{
foreach (TableCell tablecell in gridviewrow.Cells)
{
iTextSharp.text.Font font = new iTextSharp.text.Font();
font.Color = new Basecolor(GridView2.RowStyle.ForeColor);
PdfPCell pdfcell = new PdfPCell(new Phrase(tablecell.Text));
pdfcell.BackgroundColor = new Basecolor(GridView2.RowStyle.BackColor);
pdfTable.AddCell(pdfcell);
}
}
Document pdfdoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
PdfWriter.GetInstance(pdfdoc, Response.OutputStream);
pdfdoc.Open();
pdfdoc.Add(pdfTable);
pdfdoc.Close();
Response.ContentType = "application/pdf";
Response.AppendHeader("content-disposition", "attachment;filename=Employyes.pdf");
Response.Write(pdfdoc);
Response.Flush();
Response.End();
return "success";
}
ajax function call
$(document).ready(function () {
$("#Button2").click(function () {
alert("ajax call");
$.ajax
({
method: "GET",
url: "api/Employees",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("success");
},
error: function (responce) {
alert("error");
},
});
});
});
<asp:Button ID="Button1" runat="server" Style="width: 136px" Text="Export to Excel" Width="175px" />&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<asp:Button ID="Button2" runat="server" Text="Export to PDF" Width="175px" />
<br />
<br />
<div class="auto-style1" id="NewData">
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="true">
</asp:GridView>
</div>
here is my controller class
public class EmployeesController : ApiController
{
// success s = new success();
BusinessLogicLayer bal = new BusinessLogicLayer();
public string Get(string username, string password)
{
return bal.login(username, password);
}
[System.Web.Mvc.HttpPost]
public string POST(string firstname, string lastname, string username, string password, string email)
{
return bal.Register(firstname, lastname, username, password, email);
}
[System.Web.Http.HttpGet]
public string buttonclick()
{
// MessageBox.Show("come");
return bal.ExportConvert();
}
here is my business logic layer class method
public string ExportConvert()
{
success s = new success();
return s.Button3_Click();
}[enter image description here][1]
here my login page code
**<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body style="padding-top:20px;">
<div class="col-md-10 col-md-offset-1">
<div class="well">
<table class="table table-bordered">
<thead>
<tr class="success">
<th colspan="2">
Existing User Login
<a class="btn btn-success pull-right" href="Registration.html">Register</a>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>UserName</td>
<td>
<input type="text" id="username" placeholder="username"/>
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" id="password" placeholder="Password" />
</td>
</tr>
<tr class="success">
<td colspan="2">
<input type="button" id="btnlogin" class="btn btn-success" value="login" />
</td>
</tr>
</tbody>
</table>
<div class="modal fade" tabindex="-1" id="successmodel"
data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4>Success</h4>
</div>
<div class="modal-body">
<h2>Registraton success</h2>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-success">
Close
</button>
</div>
</div>
</div>
</div>
<div id="divError" class="alert alert-danger collapse">
<a id="linkClose" class="close" href="#" >×</a>
<div id="divErrorText"></div>
</div>
</div>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<script type="text/javascript" >
$(document).ready(function () {
$('#linkClose').click(function () {
$('divError').hide('fade');
})
});
$('#btnlogin').click(function () {
$.ajax({
url: '/api/Employees/?username=' + $("#username").val() + '&password=' + $("#password").val(),
method: 'Get',
contentType: 'application/json',
data: { id: 1 },
dataType: 'json',
success: function (data) {
console.log(data);
//var data = data.d;
//alert("success " + data);
if (data == 'success') {
window.location = "/success.aspx";
}
else {
alert("Wrong Username and Password");
}
/* if (data != null) {
$.each(data, function (i, obj) {
var c = new WorkflowsEntity(data[i]); //logic
self.WorkflowList.push;
});
alert("success");
//window.location.href = "/success.html";
}*/
},
error: function (jqXHR, textStatus, errorThrown) {
alert(" un correct username password ");
$('#divErrorText').text(jqXHR.responceText);
$('#divError').show('fade');
}
});
});
</script>
</body>
</html>**

asp.net mvc + Ajax.BeginForm OnBegin not firing

After reading several posts regarding this issue, it is mostly related to including
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
and the proper order of including jquery first.
<script src="~/Scripts/jquery-1.12.4.js"></script>
I think I did properly, but OnBegin is not firing still.
_Layout.cshtml:
<head>
<meta charset="utf-8" />
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<title>Test</title>
#Scripts.Render("~/bundles/modernizr")
<script src="~/Scripts/jquery-1.12.4.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/respond.min.js"></script>
<script src="~/Scripts/jquery.dataTables.js"></script>
<script src="https://cdn.datatables.net/responsive/2.1.0/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.colVis.min.js"></script>
<script src="~/Scripts/light-bootstrap-dashboard.js"></script>
<script src="~/Scripts/bootstrap-notify.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
#RenderSection("scripts", required: false)
</head>
So the order of process is:
School View:
#model Test.Models.School
<div class="editorRow">
#using (Html.BeginCollectionItem("schools"))
{
#Html.ActionLink("New Employee", "NewEmployee", "Test", new
{
#class = "btn btn-info btn-md",
data_toggle = "modal",
data_target = "#modal-container-employee"
})
</div>
<div id="modal-container-employee" class="modal fade" tableindex="-1" role="dialog">
<div class="modal-content">
<div class="modal-body">
</div>
</div>
</div>
Controller:
public ActionResult NewEmployee()
{
var newEmployee = new Employee();
return View(newEmployee);
}
Employee view:
#model Test.Models.Employee
#{
Layout = null;
}
#using (Ajax.BeginForm("PostEmployee", "Employee", new AjaxOptions
{
HttpMethod = "post",
InsertionMode = InsertionMode.Replace,
OnBegin = "closeModal"
}))
{
#Html.AntiForgeryToken()
<div id="test" class="">
<div class="modal-title title">
<input type="submit" id="submit" value="Save" /><span id="closes">x</span>
</div>
#Html.EditorFor(model => model.FullName)
</div>
}
<script>
function closeModal() {
$('#modal-container').modal('hide');
}
</script>
controller:
[HttpPost]
public ActionResult PostEmployee(Employee model)
{
try
{
var newEmployee = new Employee
{
FullName = model.FullName
};
db.Employees.Add(newEmployee);
db.SaveChanges();
return Json(new { status = "success" }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { status = "error", errorMessage = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
As a result, "success" Json is returned, but ajax is not catching it, it directly goes to the other page where it shows JSON array {"status":"success"}.
Can anyone find the problem?

MVC3 Ajax.BeginForm with javascript disabled

I'm having a problem getting a form to work without javascript being enabled.
This should be enough to go on, ask if you need to know anything else - I don't want to just put the whole solution up here!
~/Views/_ViewStart.cshtml:
#{ Layout = "~/Views/Shared/Layout.cshtml"; }
~/Views/Shared/Layout.cshtml:
#using System.Globalization; #{ CultureInfo culture = CultureInfo.GetCultureInfo(UICulture); }<!DOCTYPE html>
<html lang="#culture.Name" dir="#(culture.TextInfo.IsRightToLeft ? "rtl" : "ltr")">
<head>
<title>AppName :: #ViewBag.Title</title>
<link href="#Url.Content("~/favicon.ico")" rel="shortcut icon" type="image/x-icon" />
<link href="#Url.Content("~/apple-touch-icon.png")" rel="apple-touch-icon" />
<link href="#Url.Content("~/Content/css/site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Content/js/jquery-1.6.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/js/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/js/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/js/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/js/app.js")" type="text/javascript"></script>
#RenderSection("SectionHead", false)
</head>
<body>
<div id="page-container">
<div id="nav">
<div id="nav-user">
#{ Html.RenderAction("LoginStatus", "Account"); }
#{ Html.RenderPartial("CultureSelector"); }
</div>
</div>
<div id="page-content">
<h2>#ViewBag.Title</h2>
#RenderBody()
</div>
</div>
</body>
</html>
~/Views/Account/Index.cshtml:
#model AccountFilterModel
#{
ViewBag.Title = "Account Home";
var loadingId = "loading" + new Random().Next();
Model.FilterFormId = "filter-account-form";
}
#using (Ajax.BeginForm("List", "Account", Model, new AjaxOptions { UpdateTargetId = "result-list", LoadingElementId = loadingId }, new { id = "filter-account-form" })) {
<!-- form controls and validation summary stuff -->
<input id="filter" type="submit" value="Filter" />
<span id="#loadingId" style="display: none">
<img src="#Url.Content("~/Content/images/ajax-loader.gif")" alt="Loading..." />
</span>
}
<div id="result-list">
#{ Html.RenderAction("List", Model); }
</div>
~/Views/Account/List.cshtml:
#model FilterResultModel
#helper SortLink(AccountSort sort, SortDirection dir) {
string display = (dir == SortDirection.Ascending ? "a" : "d"); // TODO: css here
if (Model.Filter.SortBy != null && ((AccountSortModel)Model.Filter.SortBy).Sort == sort && dir == Model.Filter.SortOrder) {
#:#display
} else {
FilterModel fm = new FilterModel(Model.Filter);
fm.SortBy = AccountSortModel.SortOption[sort];
fm.SortOrder = dir;
#display
}
}
#if (Model.Results.Count > 0) {
var first = Model.Results.First();
<table>
<caption>
#string.Format(LocalText.FilterStats, Model.FirstResultIndex + 1, Model.LastResultIndex + 1, Model.CurrentPageIndex + 1, Model.LastPageIndex + 1, Model.FilteredCount, Model.TotalCount)
</caption>
<thead>
<tr>
<th>
#Html.LabelFor(m => first.Username)
<span class="sort-ascending">
#SortLink(AccountSort.UsernameLower, SortDirection.Ascending)
</span>
<span class="sort-descending">
#SortLink(AccountSort.UsernameLower, SortDirection.Descending)
</span>
</th>
<!-- other table headers -->
</tr>
</thead>
<tbody>
#foreach (AccountModel account in Model.Results) {
<tr>
<td>#Html.EncodedReplace(account.Username, Model.Filter.Search, "<span class=\"filter-match\">{0}</span>")</td>
<!-- other columns -->
</tr>
}
</tbody>
</table>
Html.RenderPartial("ListPager", Model);
} else {
<p>No Results</p>
}
Relevant part of AccountController.cs:
public ActionResult Index(AccountSort? accountSort, FilterModel model = null) {
FilterModel fm = model ?? new FilterModel();
if (accountSort.HasValue) fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
return View(fm);
}
public ActionResult List(AccountSort? accountSort, FilterModel model = null) {
FilterModel fm = model ?? new FilterModel();
if (accountSort.HasValue) fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
return Request.IsAjaxRequest() ? (ActionResult)PartialView("List", Service.Get(fm)) : View("Index", model);
}
With javascript enabled, this works fine - the content of div#result-list is updated as expected.
If I don't do the Request.AjaxRequest() and just return the PartialView, then with javascript disabled I get a page with just the content of the results on it. If I have the code as above, then I get a StackOverflowException.
How do I get this to work?
Solution
Thanks to #xixonia, I discovered the problem - here is my solution:
public ActionResult List(AccountSort? accountSort, FilterModel model = null) {
FilterModel fm = model ?? new FilterModel();
if (accountSort.HasValue)
fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
if (Request.HttpMethod == "GET")
return PartialView("List", Service.Get(fm));
if (Request.HttpMethod == "POST")
return Request.IsAjaxRequest() ? (ActionResult) PartialView("List", Service.Get(fm)) : RedirectToAction("Index", model);
return new HttpStatusCodeResult((int) HttpStatusCode.MethodNotAllowed);
}
You can use the following extension method to determine if the request is an ajax request
Request.IsAjaxRequest()
If it is, you can return a partial view, otherwise you can return a full view or redirect.
if(Request.IsAjaxRequest())
{
return PartialView("view", model);
}
else
{
return View(model);
}
edit: here's the problem:
The "List" is returning the "Index" view when the request is not an AJAX request:
public ActionResult List(AccountSort? accountSort, FilterModel model = null) {
FilterModel fm = model ?? new FilterModel();
if (accountSort.HasValue) fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
return Request.IsAjaxRequest() ? (ActionResult)PartialView("List", Service.Get(fm)) : View("Index", model);
}
The "Index" view is rendering the "List" action:
#{ Html.RenderAction("List", Model); }
AKA: Recursion.
You need to engineer a way to display your list without drawing the index page, or make your index page draw a partial view with your list modal as a parameter.

Resources