简体   繁体   English

将字典传递给 controller asp.net mvc

[英]pass dictionary to controller asp.net mvc

I am wanting to pass a dictionary of type <int,int> to my controller via an Ajax post.我想通过 Ajax 帖子将<int,int>类型的字典传递给我的 controller。 The main reason here is the post may have between 1-3 key value pairs here (none of these values are known at compile time) and in the future it may go up to 5.这里的主要原因是这里的帖子可能有 1-3 个键值对(在编译时这些值都不知道),将来它可能 go 最多 5 个。

Also in the post I have to pass in some other data, such as Id and name, which all works as normal.同样在帖子中,我必须传递一些其他数据,例如 Id 和 name,它们都可以正常工作。

How would I construct this dictionay in the javascript then send it via the JQuery post and finally receive it on the controller to process?我将如何在 javascript 中构建这个字典,然后通过 JQuery 帖子发送它,最后在 controller 上接收它进行处理?

Edit 2: I have decided to just solve this with a post for each value instead of trying to pass a dictionary.编辑 2:我决定用每个值的帖子来解决这个问题,而不是尝试传递字典。

EDIT: Here is my source for the function so you can see what I am trying:编辑:这是我的 function 的来源,所以你可以看到我在尝试什么:

function BindAddMenuItem() {
        $(".AddMenuItem").click(function (e) {
            e.preventDefault();

            //get header id from link by removing addmenuitem from this.id
            var currentId = $(this).attr("id").replace("AddMenuItem", "");

            //get itemnumber, itemname, itemdetails from textboxes with same header id
            var restaurantId = jQuery.trim($("#RestaurantId").val());
            var itemNumber = jQuery.trim($("#ItemNumber" + currentId).val());
            var itemName = jQuery.trim($("#ItemName" + currentId).val());
            var itemDetails = jQuery.trim($("#ItemDetails" + currentId).val());

            var costs = new Object();
            //select all textboxes with class "Header" + currentId
            $(".Header" + currentId).each(function (i) {
                var optionId = $(this).attr("id").replace("Option", "");
                costs[optionId] = $(this).val();
            });


            $.ajax(
            {
                type: "POST",
                url: "/Menu/AddMenuItem",
                data: "reastaurantId=" + restaurantId + "&menuHeaderId=" + currentId + "&itemNumber=" + itemNumber + "&itemName=" + itemName + "&itemDetails=" + itemDetails + "&costs=" + costs,
                dataType: "html",
                success: function (result) {
                    var domElement = $(result);
                    $("#MenuContainer").replaceWith(domElement);
                    var newNum = parseInt(itemNumber) + 1;
                    $("#ItemNumber" + currentId).val(newNum);
                    BindAllBehaviours();
                }
            });
        });

    }

Something like (javascript)像(javascript)

dict = new Object();
dict['12'] = 5;
dict['13'] = 6;
dict['1000'] = 21;
dict['9'] = 13;
dict['13'] = 48;

$.post('/client.mvc/mypostaction/', { myDictionary: dict });

You can then post the dict object to your controller using a Dictionary<int, int> as property type.然后,您可以使用Dictionary<int, int>作为属性类型将dict对象发布到您的控制器。

ActionResult MyPostAction(Dictionary<string, int> myDictionary)

edit from author's code second time:第二次编辑作者的代码:

The following works for me, when having a Dictionary<string, int> kvPairs .当有Dictionary<string, int> kvPairs时,以下对我Dictionary<string, int> kvPairs <int, int> isn't going to work after all. <int, int>毕竟是行不通的。

Make your post like:让你的帖子像:

var dict = new Object();
dict['13'] = 9;
dict['14'] = 10;
dict['2'] = 5;

$.post('controller.mvc/Test', { 'kvPairs': dict }, function(obj) { $('#output').html(obj.Count); }); 

JavaScript object / dictionary has to be passed as a list of key-value pairs to ASP.NET MVC controller when Dictionary<TKey, TValue> is expected.当期望Dictionary<TKey, TValue>Dictionary<TKey, TValue> JavaScript 对象/字典必须作为键值对列表传递给 ASP.NET MVC 控制器。 Example:例子:

If you have a dictionary like this:如果你有这样的字典:

public Dictionary<string, decimal?> SomeMapping { get; set; }

then you have to use something like this in your JavaScript:那么你必须在你的 JavaScript 中使用这样的东西:

var sourceMapping = { a: 1, b: 1.5, c: null };
var SomeMapping = [];
for (var key in sourceMapping) {
    if (sourceMapping.hasOwnProperty(key)) {
        SomeMapping.push({ Key: key, Value: sourceMapping[key] });
    }
}

I've used this approach in asynchronous POST request (sent using jQuery) that had content type set to 'application/json' (this may or may not be important in your case).我在内容类型设置为'application/json'异步 POST 请求(使用 jQuery 发送)中使用了这种方法(这在您的情况下可能重要也可能不重要)。

Client (JavaScript):客户端(JavaScript):

var dict = new Object();
dict.Key1 = "Value1"
dict.Key2 = "Value2"

$.post('/YourController/YourAction/', dict);

NOTE: The "dict" objects gets serialized behind the scenes before being sent to your action.注意:“dict”对象在发送到您的操作之前会在幕后序列化。

Server:服务器:

public ActionResult YourAction()
{
    string postData = string.Empty;
    using (StreamReader sr = new StreamReader(Request.InputStream))
    {
        postData = sr.ReadToEnd();
    }    

    //Load post data into JObject (Newtonsoft.Json)
    JObject o = JObject.Parse(postData);

    //Extract each key/val 
    string val1 = (string)o["Key1"];

    //Do whatever....
}

None of these worked for me except for mczers , but he doesn't show all the steps, and makes it difficult when you're trying to remember how you set up an ajax request.除了mczers之外,这些都不适合我,但是他没有显示所有步骤,并且当您试图记住如何设置 ajax 请求时会变得很困难。 So I wanted to put everything that actually just works.所以我想把所有真正有效的东西都放进去。 First, in JavaScript:首先,在 JavaScript 中:

        var validDict = new Array();
        validDict[0] = { key: 1, value: 4 }
        validDict[1] = { key: 42, value: 5}


var path = "@Url.Action("ControllerName", "ActionName")";
        $.ajax({
            url: path,
            type: "POST",
            data: JSON.stringify(validDict),
            contentType: "application/json; charset=utf-8",
            async:false,
            success: function(status, xhr)
            {

                alert(status);
              
            },
            error: function(xhr, status, error)
            {
                alert(error);
               

            }});

Then in your controller:然后在您的控制器中:

        [HttpPost]
        public ActionResult ActionName(Dictionary<int, int> validDict)
        {
        // doStuff();
        return Content("Success");
        }

A dictionary of the kind IDictionary<string, string> on server side can be posted from javascript like服务器端的 IDictionary<string, string> 类型的字典可以从 javascript 中发布,例如

{"Key1": "Value1", "Key2": "Value2"}

on the Server Side in ASP.NET Web API在 ASP.NET Web API 中的服务器端

[HttpPost]
public IHttpActionResult([FromBody]IDictionary<string, string> requestParam){
}

Above example is for an Http POST with the Json data in the Body上面的例子是一个 Http POST,在正文中包含 Json 数据

For passing a Dictionary I found the following working answer: submitting-a-dictionary-to-an-asp-net-mvc-action为了传递字典,我找到了以下工作答案: submit-a-dictionary-to-an-asp-net-mvc-action

@model WebApplication3.Controllers.ExampleViewModel @{ ViewBag.Title = "New";
var first = Guid.NewGuid(); var second = Guid.NewGuid(); }

<h2>New</h2>

@using (Html.BeginForm(new { action = "create", controller = "home" })) {
foreach (var kvp in Model.Values) {
<p>
  <input type="text" name="Model.Values[@first].Key" value="@kvp.Key" />
  <input type="text" name="Model.Values[@first].Value" value="@kvp.Value" />
  <input type="hidden" name="Model.Values.Index" value="@first" />
</p>
}

you have to generate A Guid for the dictionary index, and you have to create 3 inputs, one for the Key, one for the Value and one for the Index of the Dictionary您必须为字典索引生成 A Guid,并且必须创建 3 个输入,一个用于键,一个用于值,一个用于字典索引

Also I have submited using Jquery with the following:我还使用 Jquery 提交了以下内容:

$('form#frmFormId').submit(function (e) {
        e.preventDefault();
        var formData = new FormData(this);
        //debugger;
        $('#cover-spin').show(100);
        $.ajax({
            type: 'POST',
            url: $(this).attr('action'),
            data: formData,
            processData: false,
            contentType: false            
        }
        );
        return false;
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM