I need to get a record count out of a successful Ajax post.
Since the datatype is "html", I cannot check for a specific record count via json.
So, what I'm doing is trying to apply the record count to a ViewBag variable (from a Controller method) and assign it to a hidden html field that I can check after the post. If 0 records are returned, I can display a proper message to the user.
My process is as follows: I'm using MVC 5.2
- In the GET for the Controller method, I set the ViewBag variable
count to 1 (for a test. Ideally, it should be 0).
- The View assigns the value of the ViewBag variable to the JS variable.
- In the POST, I get the record count from the records retrieved and assign it to the ViewBag property.
- The View again should assign the value of the ViewBag variable to the JS variable.
- When the POST finishes, the JS variable checks if the value is 0 and then would display the proper message.
However, the issue I'm having is that the initial value I set during the GET of 1, never changes.
I've verified during debugging, that when the POST occurs in the controller, the ViewBag property is set to 0 (no records returned). I purposely set the initial value to 1 (in the GET) just to see if the value has changed.
Can someone please inform me why the JS variable is not being updated to the value of 0 (step 4 above) after the POST?
Here is my code:
Controller
// GET: Customers/CustomerProjects/Details
public async Task<ActionResult> Details()
{
ViewBag.projectCount = "1";
ViewBag.CustomerEmail = await db.GetCustomerDDLAsync();
return View();
}
[HttpPost]
// POST: Customers/CustomerProjects/Details/5
public async Task<ActionResult> Details(short? id)
{
if (id == null)
{
return View("IDIsNull");
}
ViewBag.CustomerEmail = await db.GetCustomerDDLAsync();
Customer customer = await db.GetProjectsByCustomerIDAsync(id);
if (customer == null)
{
return View("ObjectModelNull");
}
ViewBag.projectCount = customer.Projects.Count.ToString();
return View(customer);
}
VIEW
@Html.Hidden("projCnt", (string)(ViewBag.projectCount))
JS
if ($('#projCnt').val() == "0")