开发者

How can I call a new web page from javascript / jQuery

开发者 https://www.devze.com 2023-03-15 03:33 出处:网络
I have a button like this: <button id=\"CreateButton\" title=\"Create Task\">Create Task</button>

I have a button like this:

<button id="CreateButton" title="Create Task">Create Task</button>

I wrote code to capture the click event:

        $('#CreateButton').click(function (event) {
           event.preventDefault
           var datastore = $("#SelectedDatastore").val();
           xxxxxx
        });

But I want make the clicking call an action me开发者_运维知识库thod on my MVC controller with some parameters. For example the paramater and value of datastore.


If you just want to go to another page, you could change the location:

window.location = "MyPage.aspx?paramater=MyParamValue";

Or if you don't want to change the current page, but just to execute an action, use jQuery.get()

$.get("MyPage.aspx", { paramater: "MyParamValue" }, function(data) {
  alert("Response from the server: " + data);
});


XMLHttpRequest is the standard solution here.


If you want to actually change the page that is loaded in the browser, you would need to set the window.location attribute to the URL of the new page you want to visit. This will cause the browser to browse to that page as if the user had typed it in the address bar.


Since it is a Create operation, it should not be done with a GET request, like changing window.location. Instead you have to do it with POST Request. Check this code:

$('#CreateButton').click(function (event) {
    var theUrl = '<%= ResolveUrl("~/SomethingControlloer/Create")%>';

    $.ajax({
        type: "POST",
        url: theUrl,  
        data: { },   // Data to send with request
        dataType: "json",
        success: function () {},
        failure: function () { alert("Error!"); }
    });
});

Of course, for ResolveUrl to work, you should already have a registered MVC route in Global.asax.cs, and your action method should have [HttpPost] attribute.

0

精彩评论

暂无评论...
验证码 换一张
取 消