9

I have a MVC 5 website that displays log file entries in a grid and provides a search capability. I have both the search criteria and the grid.mvc grid on the Index page. When the user enters the search criteria and clicks the submit button I want the ProcessLogEntries method (below) to update the Model and refresh the Index.cshtml page - not navigate to a non-existent ProcessLogEntries page!

Basically, I want this application to behave like an Single Page Application...

How do I set up the HomeController.ProcessLogEntries() method to accomplish this?

public class HomeController : Controller
{
    public LogsResearchViewModel ViewModel  { get; set; }

    public HomeController()
    {
        ViewModel = new LogsResearchViewModel();
    }

    public ActionResult Index()
    {
        ViewBag.Message = "";
        return View(ViewModel);
    }

    [HttpPost]
    public ActionResult ProcessLogEntries(string txtSearchFor, string txtDateStart, string txtDateStop, string txtSource)
    {
        ViewBag.Message = "";

        string searchFor = txtSearchFor.ToString();
        DateTime start = DateTime.Parse(txtDateStart.ToString());
        DateTime stop = DateTime.Parse(txtDateStop.ToString());
        string source = txtSource.ToString();

        ViewModel.GetProcessLogEntries(searchFor, start, stop);
        ViewModel.GetErrorLogEntries(source, searchFor, start, stop);

        return View(ViewModel);
    }
}
4
  • 2
    You will need AJAX triggered by your button instead of a form submission. Then return a partial view from your ProcessLogEntries action. Here is an example with partial views.
    – Jasen
    Sep 24, 2014 at 18:13
  • You could also return json from your ProcessLogEntries action and consume that object in javascript if you don't need a much of a view response.
    – Jasen
    Sep 24, 2014 at 18:17
  • Jasen, How would I update the Model using AJAX/JSON? I'm going to your referenced link; hopefully, I'll find the answer there... :-)
    – MilesT
    Sep 24, 2014 at 18:26
  • I hope that I made it clear that I need the LogsResearchViewModel ViewModel to be updated (which I can pass values into the Controller to do so); to refresh the View UI's datagrid. I just don't want to change pages after doing so... IDK how to update the ViewModel via AJAX, so IDK how to make that approach work.
    – MilesT
    Sep 24, 2014 at 18:36

2 Answers 2

10

If you want to update a page without reloading you'll need AJAX. Here's an outline to get started.

Partial View

Create a main view that will act as a "frame". An empty div will act as your placeholder for your grid.

<h2>Main View</h2>
<div id="grid"><!-- grid paceholder --></div>

<script>
    // ajax script here
</script>

Now create a partial view to hold your grid

_GridPartial

@model LogsResearchViewModel

@Html.Grid(Model)
<button id="btnTrigger">Process</button>

If you want you can embed this so the first time Main view loads you will have a populated grid.

<h2>Main View</h2>
<div id="grid">@{Html.RenderAction("LoadGrid")}</div>

With the supporting action

public ActionResult LoadGrid()
{
    var model = new LogsResearchViewModel() { ... };
    return PartialView("_GridPartial", model);
}

Now setup the AJAX to insert into the placeholder.

<script>
    $("#grid").on("click", "#btnTrigger", function(e) {
        $.ajax({
            url: "/ProcessLogEntries",
            type: "post",
            data: {
                txtSearchFor: "// txtSearch.val()",
                txtDateStart: "",
                txtDateStop: "",
                txtSource: ""
            }
        })
        .done(function(result) {
            $("#grid").html(result);
        });
     });
</script>

And the action returns a partial view

[HttpPost]
public ActionResult ProcessLogEntries(
    string txtSearchFor, string txtDateStart,
    string txtDateStop, string txtSource)
{
    var model = new LogsResearchViewModel();
    // ...
    return PartialView("_GridPartial", model);
}

After triggering the post the partial result replaces the grid div content.

JSON

If your grid supports JSON just return the model

 [HttpPost]
 public ActionResult ProcessLogEntries(...)
 {
     var model = new LogsResearchViewModel();
     // ...
     return Json(model);
 }

Then handle in javascript

...
.done(function(jsonResult) {
    console.log(jsonResult);  // should match LogsResearchViewModel
    loadGrid(jsonResult);     // pass off to grid's javascript
});
1
  • 1
    Nice and simple 'tutorial' man. I just completed my partialview, but was missing a few pieces that I did find in this 'tutorial'. Thanks =)
    – Paramone
    Aug 17, 2017 at 10:52
0

You will need to return your model. You can keep your view and extract via javascript the model from the view, or you can have a JsonResult and return only the serialized string.

From javascript side, trigger this from a button or the event of your wish.

var params = ["data","data", "data"];

$.ajax({
  type: "POST",
  url: /ProcessLogEntries,
  data: params,
  success: function(data, statusRespoonse, xhr){
   //extract your model from data or return your model via jsonresult by changing the Controller's return type.

    yourModel = data;
   },
  dataType: "json"
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.