Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Chris Foot 61 posts 93 karma points
    Sep 12, 2014 @ 14:25
    Chris Foot
    0

    Saving multiple values against a field from MVC controller

    Hi All,

    I'm really new to both Umbraco and MVC and I have just discovered the multiple textbox editor type which is fantastic for getting options into dropdowns/checkbox lists but what I can't work out is how to save data back into an umbraco model with one of these fields. In my editor I have:

    <div class="row checkbox-list">
    @foreach (var o in Model.LearningObjectives)
    {
        <label><input type="checkbox" name="SelectedLearningObjectives" value="@o" /> @o</label>
    }
    </div>
    

    Which comes back to my controller as a string[]. Unfortunately, when I try and save it back to a document (in this case a member) like this:

    member.SetValue("learningObjectives", model.SelectedLearningObjectives);
    

    I get:

    The best overloaded method match for 'Umbraco.Core.Models.ContentBase.SetPropertyValue(string, string)' has some invalid arguments

    Am I going about this all wrongly? Is there a better way to store multiple selections against a document?

    Thanks

    Chris

  • Tom van Enckevort 107 posts 429 karma points
    Sep 12, 2014 @ 15:34
    Tom van Enckevort
    0

    The second parameter in the SetValue method has to be a string as well. This is the actual value that will be stored in the database. So in your case you probably want to convert your string array to a comma-separated string (or use another character as the separator):

    string selectedObjectives = string.Join(",", model.SelectedLearningObjectives);
    member.SetValue("learningObjectives", selectedObjectives);
    

    (Note that you need to a null-check as well on your array, in case no objectives were selected).

    And obviously you need to convert things back again when you read the property value:

    string[] selectedObjectives = member.GetValue<string>("learningObjectives")).Split(new char[] { ',' });
    
  • Chris Foot 61 posts 93 karma points
    Sep 12, 2014 @ 16:25
    Chris Foot
    0

    Hi Tom,

    This approach didn't work exactly as I wanted. Once saved, the multiple textbox editor just had one text box with the selected values separated by the ,. You did prompt me to wonder how the multiple textboxes were stored in the database though so after a little sql profiling I discovered that they are stored with line breaks so replacing your joining code with

    string selectedObjectives = string.Join(Environment.NewLine, model.SelectedLearningObjectives);
    

    allows it to save and show the options selected correctly in a multiple text box in the backend. I hope this helps anyone else who stumbles across this in the future.

    Thanks for your help

    Chris

Please Sign in or register to post replies

Write your reply to:

Draft