Sllix
Sllix

Reputation: 606

Pass dictionary from view to controller after form submit

Razor view:

@using (Html.BeginForm("Move", "Details", new { dict= dictionary}, FormMethod.Post)) {
    //table with info and submit button
    //dictionary => is a dictionary of type <Sales_Order_Collected, string>
}

Controller action:

[HttpPost]
public string Move(Dictionary<Sales_Order_Collected, string> dict) {
    return "";
}

Is there a way to pass the model dictionary to the controller? Because my parameter is always null.

Upvotes: 3

Views: 4290

Answers (2)

NatalyaKst
NatalyaKst

Reputation: 333

Here is my Html helper for any dictionary:

public static IHtmlString DictionaryFor<TModel, TKey, TValue>(this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, IDictionary<TKey, TValue>>> expression)
{
    ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

    IDictionary<TKey, TValue> dictionary = (IDictionary<TKey, TValue>)metaData.Model;

    StringBuilder resultSB = new StringBuilder();

    int i = 0;

    foreach (KeyValuePair<TKey, TValue> kvp in dictionary)
    {
        MvcHtmlString hiddenKey = htmlHelper.Hidden($"{metaData.PropertyName}[{i}].Key", kvp.Key.ToString());
        MvcHtmlString hiddenValue = htmlHelper.Hidden($"{metaData.PropertyName}[{i}].Value", kvp.Value.ToString());

        resultSB.Append(hiddenKey.ToHtmlString());
        resultSB.Append(hiddenValue.ToHtmlString());

        i++;
    }

    return MvcHtmlString.Create(resultSB.ToString());
}

Call it in a View like this:

@Html.DictionaryFor(model => model.AnyDictionary)

Upvotes: 0

karaxuna
karaxuna

Reputation: 26930

you can not pass dictionary through route values. You can do something like this:

@using (Html.BeginForm("Move", "Details", null, FormMethod.Post)) {
    <input type="text" name="[0].Key" value="first key"/>
    <input type="text" name="[0].Value" value="first value"/>

    <input type="text" name="[1].Key" value="second key"/>
    <input type="text" name="[1].Value" value="second value"/>
}

This will post Dictionary. The idea for complex objects is the same

Upvotes: 6

Related Questions