最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - How to send data from javascript to ASP.NET MVC controller using URL - Stack Overflow

programmeradmin1浏览0评论

I need some help. I write little app using ASP.NET MVC4 with JavaScript and Knockout and I can't send data from javascript to MVC Controller and conversely. For example, the part of JS looks like that:

JavaScript

self.Employer = ko.observable();
self.AboutEmployer = function (id) {
            $.ajax({                    
                    Url.Action("GetEmployer", "Home")
                    cache: false,
                    type: 'GET',
                    data: "{id:" + id + "}",
                    contentType: 'application/json; charset=utf-8',
                    dataType: "json",
                    success: function (data) {
                        self.Employer(data);
                    }
                }).fail(
                function () {
                    alert("Fail");
                });
         };

In ASP.NET MVC Home Controller I'm getting employer by ID and return it as Json:

C#

public JsonResult GetEmployer(int id)
    {
        var employer = unit.Repository<Employer>().GetByID(id);
        return Json(employer, JsonRequestBehavior.AllowGet);
    }

My View return another Controller (Home/KnockOutView). My View also gets another objects and depending what recieve, has different look:

HTML

...
<b>About Company: </b><a href="#" data-bind="click: $root.AboutEmployer.bind($data, Vacancy().EmployerID)">
<span data-bind="    text: Vacancy().Employer"></span></a>
<div data-bind="if: Vacancy">
    <div id="VacancyDescription"><span data-bind="text:DescriptionShort"></span>
    </div>
</div>
<div data-bind="if: Employer">
    <div data-bind="text: Employer().EmployerDescription"></div>
</div>

Everything works great, I receive Vacancy and Employer objects in JS and show it in HTML using Knockout, but my URL all time still the same!!! But I want to change URL all time, when i'm getting Vacancy or Employer. For example, if I want to get Employer, using method GetEmployer, URL should looks like that: ~/Home/GetEmployer?id=3 If I change this string of Code Url.Action("GetEmployer", "Home") at url: window.location.href = "/home/GetEmployer?id=" + id URL will be changed, but Controller returns me an Json object and shows it in window in Json format. Help me, please, to change URL and get information in Controller from URL. Thanks.

I need some help. I write little app using ASP.NET MVC4 with JavaScript and Knockout and I can't send data from javascript to MVC Controller and conversely. For example, the part of JS looks like that:

JavaScript

self.Employer = ko.observable();
self.AboutEmployer = function (id) {
            $.ajax({                    
                    Url.Action("GetEmployer", "Home")
                    cache: false,
                    type: 'GET',
                    data: "{id:" + id + "}",
                    contentType: 'application/json; charset=utf-8',
                    dataType: "json",
                    success: function (data) {
                        self.Employer(data);
                    }
                }).fail(
                function () {
                    alert("Fail");
                });
         };

In ASP.NET MVC Home Controller I'm getting employer by ID and return it as Json:

C#

public JsonResult GetEmployer(int id)
    {
        var employer = unit.Repository<Employer>().GetByID(id);
        return Json(employer, JsonRequestBehavior.AllowGet);
    }

My View return another Controller (Home/KnockOutView). My View also gets another objects and depending what recieve, has different look:

HTML

...
<b>About Company: </b><a href="#" data-bind="click: $root.AboutEmployer.bind($data, Vacancy().EmployerID)">
<span data-bind="    text: Vacancy().Employer"></span></a>
<div data-bind="if: Vacancy">
    <div id="VacancyDescription"><span data-bind="text:DescriptionShort"></span>
    </div>
</div>
<div data-bind="if: Employer">
    <div data-bind="text: Employer().EmployerDescription"></div>
</div>

Everything works great, I receive Vacancy and Employer objects in JS and show it in HTML using Knockout, but my URL all time still the same!!! But I want to change URL all time, when i'm getting Vacancy or Employer. For example, if I want to get Employer, using method GetEmployer, URL should looks like that: ~/Home/GetEmployer?id=3 If I change this string of Code Url.Action("GetEmployer", "Home") at url: window.location.href = "/home/GetEmployer?id=" + id URL will be changed, but Controller returns me an Json object and shows it in window in Json format. Help me, please, to change URL and get information in Controller from URL. Thanks.

Share Improve this question asked Sep 23, 2013 at 17:39 Taras StrizhykTaras Strizhyk 1351 gold badge2 silver badges9 bronze badges 1
  • You've got to be careful when posting JSON. Your data is not valid JSON, because it's missing the quotes around the property name. The easiest way to get a JSON string is to use JSON.stringify on a regular javascript object, rather than trying to build the string yourself. (Make sure you're using a reasonably recent browser (IE8+ or a real browser), or using a library like json2.js if you have to support IE7)) – Joe Enos Commented Sep 23, 2013 at 17:57
Add a comment  | 

5 Answers 5

Reset to default 5

Try below code, hope helps you

This code works %100 , please change below textbox according to your scenario

HTML

<input type="text" id="UserName" name="UserName" />
<input type="button" onclick="MyFunction()"value="Send" />

<div id="UpdateDiv"></div> 

Javascript:

function MyFunction() {
    var data= {
        UserName: $('#UserName').val(),
    };
    $.ajax({
        url: "/Home/GetEmployer",
        type: "POST",
        dataType: "json",  
        data: JSON.stringify(data),
        success: function (mydata) {
            $("#UpdateDiv").html(mydata);
            history.pushState('', 'New URL: '+href, href); // This Code lets you to change url howyouwant
        });
        return false;
    }
}

Controller:

public JsonResult GetEmployer(string UserName)
{
    var employer = unit.Repository<Employer>().GetByID(id);
    return Json(employer, JsonRequestBehavior.AllowGet);
}

Here is my controller action.

[HttpPost]
    public ActionResult ActionName(string x, string y)
    {
        //do whatever
        //return sth :)

    }

and my post action is here.

<script type="text/javascript">
        function BayiyeCariEkle(){

           var sth= $(#itemID).text();

           var sth2= $(#itemID2).text();

           $.post("/ControllerName/ActionName", { x: sth, y: sth2});

         }
</script>

use data parameters like this {id:id, otherPara:otherParaValue}

 $.ajax({                    
     url:Url.Action("GetEmployer", "Home")
     type: 'GET',
     data: {id:id},
     contentType: 'application/json; charset=utf-8',
     dataType: "json",
     success: function (data) {
         alert(data)
     }
 });

Due to MVC being slightly annoying in it's processing of routes to the same view, I've had success doing this:

self.Employer = ko.observable();
self.AboutEmployer = function (id) {
            $.ajax({                    
                    url: "@Url.Action("GetEmployer", "Home", new { id = "PLACEHOLDER"})".replace("PLACEHOLDER", id),
                    cache: false,
                    type: 'GET',
                    contentType: 'application/json; charset=utf-8',
                    dataType: "json",
                    success: function (data) {
                        self.Employer(data);
                    }
                }).fail(
                function () {
                    alert("Fail");
                });
         };

You can use standard url: "@Url.Action("GetEmployer", "Home")/" + id, but on refresh, the route with the existing ID stays in subsequent calls, so it begins appending the id, which obviously doesn't work. By specifying the ID in call, that behavior is no longer present.

The best way for navigation on my opinion, is to use sammy.js. Here is a post about that kazimanzurrashid.com

发布评论

评论列表(0)

  1. 暂无评论