Amit
Amit

Reputation: 319

Refresh content on button click in MVC through action method

This is my controller.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return Content(DateTime.Now.ToLongTimeString());
    }
}

This is my view.

<script src="../../Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
    $("input").click(function () {
        $("#div1").load('@Url.Action("Index")');
    });
</script>
<div id="div1"></div>
<input type="button" id="button1" value="Refresh"/>

I need to refresh the current time after I run the project. But after running the project the button is not showing up.

If I refresh the page with the F5 button, the time is getting refreshed, but I want to do it on button click.

Upvotes: 1

Views: 7302

Answers (1)

user3559349
user3559349

Reputation:

You need to change the script to

$( document ).ready(function() {
    $("#button1").click(function () {
        $("#div1").load('@Url.Action("Index")');
    });
});

so that it is handling the .click() event of the button identified by id="button1" and you need to wrap the script in document ready because you render the elements after your script (they do not exist at the time the script is parsed in the view). Alternatively, move the script to immediately before the closing </body> tag (after the elements)

Upvotes: 2

Related Questions