C# 如何使用 URL 将数据从 javascript 发送到 ASP.NET MVC 控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18965503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:43:40  来源:igfitidea点击:

How to send data from javascript to ASP.NET MVC controller using URL

c#javascriptasp.netknockout.js

提问by Taras Strizhyk

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 和 Knockout 的 ASP.NET MVC4 编写了小应用程序,但我无法将数据从 javascript 发送到 MVC 控制器,反之亦然。例如,JS 的部分是这样的:

JavaScript

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:

在 ASP.NET MVC Home Controller 中,我通过 ID 获取雇主并将其作为 Json 返回:

C#

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:

我的视图返回另一个控制器(Home/KnockOutView)。我的视图还获得了另一个对象,并根据收到的内容具有不同的外观:

HTML

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=" + idURL 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.

一切正常,我在 JS 中接收 Vacancy 和 Employer 对象并使用 Knockout 在 HTML 中显示它,但我的 URL 始终保持不变!!!但是当我得到空缺或雇主时,我想一直更改 URL。例如,如果我想获取 Employer,使用 GetEmployer 方法,URL 应如下所示: ~/Home/GetEmployer?id=3 如果我更改URLUrl.Action("GetEmployer", "Home")处的此代码字符串 url: window.location.href = "/home/GetEmployer?id=" + id将更改,但 Controller 返回给我一个 Json 对象和以 Json 格式在窗口中显示它。请帮助我更改 URL 并从 URL 获取控制器中的信息。谢谢。

采纳答案by Soner Sevinc

Try below code, hope helps you

试试下面的代码,希望对你有帮助

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

此代码有效 %100,请根据您的情况更改以下文本框

HTML

HTML

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

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

Javascript:

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);
}

回答by Jaime Torres

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

由于 MVC 在处理到同一视图的路由时有点烦人,我已经成功地做到了这一点:

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.

您可以使用 standard url: "@Url.Action("GetEmployer", "Home")/" + id,但在刷新时,具有现有 ID 的路由保留在后续调用中,因此它开始附加 id,这显然不起作用。通过在调用中指定 ID,该行为不再存在。

回答by Ankush Jain

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

使用这样的数据参数 {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)
     }
 });

回答by Taras Strizhyk

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

我认为导航的最佳方式是使用 sammy.js。这是一篇关于kazimanzurrashid.com 的帖子

回答by Burk

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>