chiapa
chiapa

Reputation: 4412

Updating layout part dynamically

C# asp.net MVC project: I have my index page with a button in it, I want to press it and update the same page with some results.

Here's some code:

The View: (with a button that calls the getConfig method in the controller)

@{
    ViewBag.Title = "Home Page";
}

<form method="get" action="/Home/GetConfig/" >
    <input type="submit" value="Get Config WS" />
</form>

<p>
    @ViewBag.totalRecords
</p>

The controller:

 public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Test webservices";

            return View();

        }

        public void getConfig()
        {
            string totalRecords = string.Empty;

            wsConfig.config_pttClient client = new wsConfig.config_pttClient();
            wsConfig.getConfigInput gci = new wsConfig.getConfigInput();
            wsConfig.getConfigOutput gco = new wsConfig.getConfigOutput();

            gco = client.getConfig(gci);

            totalRecords = gco.result.totalRecords.ToString();

            ViewBag.totalRecords = totalRecords;

        }

I want to press the view's button and show the totalRecords on the same page.

How can I achieve this?

Upvotes: 1

Views: 107

Answers (2)

Amit
Amit

Reputation: 823

Try This:

Replace your input button code with the following code :

<input type="submit" id="btnSave" name="BtnSave" value="Get Config WS" /> 

Then in controller change the whole code for this code:

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Test webservices";

            return View();

        }

        public ActionResult getConfig()
        {
          return View();
        }

    [HttpPost]
           public ActionResult getConfig(FormCollection Form)
            {
              if(Form["BtnSave"]!=null)
               {

                string totalRecords = string.Empty;

                wsConfig.config_pttClient client = new wsConfig.config_pttClient();
                wsConfig.getConfigInput gci = new wsConfig.getConfigInput();
                wsConfig.getConfigOutput gco = new wsConfig.getConfigOutput();

                gco = client.getConfig(gci);

                totalRecords = gco.result.totalRecords.ToString();

                ViewBag.totalRecords = totalRecords;
              }
              return View();
            }

Hopefully it works...!

Upvotes: 0

Complexity
Complexity

Reputation: 5820

Edit: There might be other solutions, (if you don't mind updating your entire page) but this how I generally do it.

Ok, there are a couple of things that you need to change in order to make it work:

Create a new partial view that contains just the part that you would like to update (and wrap it an element with an id). In this example, let's call it 'Partial_TotalCount'. This partial view will contain the following code:

<div id="updated">
    <p>
        @ViewBag.totalRecords
    </p>
</div>

Now, change your original view so that it includes the partial view:

@{
    ViewBag.Title = "Home Page";
}

<form method="get" action="/Home/GetConfig/" >
    <input type="submit" value="Get Config WS" />
</form>

@Html.Partial("Partial_TotalCount", @Model)

Now, update your controller to work with an ajax request. This would make your controller looks like:

public ActionResult Index()
{
    ViewBag.Message = "Test webservices";

    if (Request.IsAjaxRequest())
    { 
        getconfig(); 
        return PartialView("Partial_TotalCount");
    }

    return View();
}

Now, you need to be able to submit the page when you click the button. This can be done through javascript:

First your javascript function that will update the contents:

<script type="text/javascript">
    function Refresh() {
        $.ajax({
            url: '/Home/Index',
            type: "GET",
            dataType: "html",
            success: function(data) {
                $("#updated").html(data);
            },
            error: function() { alert('Refreshing error.'); }
        });
    }
</script>

You just need to add an onclick on your button. And you can remove the form tags from around your form aswell.

Edit: As requested by the questioner, I provide a bit of explanation on the Javascript function itself:

$.ajax means that we are doing an Ajax request. It means that we are doing some asynchronous requests with the server.

Then a couple of parameters are passed:

  • Url: The url that should be executed. In your example, the code behind the url "Home/GetConfig" get's executed.
  • Type: The type of submit that you want to do (POST, GET, ...)
  • dataType: The type we are expecting back from the server.
  • Success: The piece of javascript that needs to execute when complete. (In this case, update the DIV element with the id "WithCss" with the contents that are received with the url "Home/Getconfig".
  • Error: A function that is executed when the request failed for some reason.

There are a lot of other parameters you can pass (for example if you need to pass an id, and others.

For more explanation, please look at the original documentation.

Also, consider marking this answer as accepted.

I hope it works.

Upvotes: 1

Related Questions