ASP.NET MVC UpdateModel with a sorta complex data entry field
Asked Answered
D

1

10

how do i do the following, with an ASP.NET MVC UpdateModel? I'm trying to read in a space delimeted textbox data (exactly like the TAGS textbox in a new StackOverflow question, such as this) into the model.

eg.

<input type="Tags" type="text" id="Tags" name="Tags"/>

...

public class Question
{
    public string Title { get; set; }
    public string Body { get; set; }
    public LazyList<string> Tags { get; set; }
}

....

var question = new Question();
this.UpdateModel(question, new [] { "Title", "Body", "Tags" });

the Tags property does get instantiated, but it contains only one item, which is the entire data that was entered into the Tags input field. If i want to have a single item in the List (based upon Splitting the string via space) .. what's the best practice do handle this, please?

cheers!

Dwt answered 12/11, 2008 at 6:28 Comment(0)
E
8

What you need to do is extend the DefaultValueProvider into your own. In your value provider extend GetValue(name) to split the tags and load into your LazyList. You will also need to change your call to UpdateModel:

UpdateModel(q, new[] { "Title", "Body", "Tags" }, 
   new QuestionValueProvider(this.ControllerContext));

The QuestionValueProvider I wrote is:

 public class QuestionValueProvider : DefaultValueProvider
    {
        public QuestionValueProvider(ControllerContext controllerContext)
            : base(controllerContext)
        {
        }
        public override ValueProviderResult GetValue(string name)
        {
            ValueProviderResult value = base.GetValue(name);
            if (name == "Tags")
            {
                List<string> tags = new List<string>();
                string[] splits = value.AttemptedValue.Split(' ');
                foreach (string t in splits)
                    tags.Add(t);

                value = new ValueProviderResult(tags, null, value.Culture); 
            }
            return value;
        }
    }

Hope this helps

Emersed answered 12/11, 2008 at 10:24 Comment(4)
yep! sure does! now i'm wondering if it's worth doing all that, instead of just doing an UpdateModel with "title" and "body", then manually setting the Tags property, after i do call Request["Tags"] and split that?Dwt
@John - just to continue this thread, when i added the <%=Html.ValidationMessage("Tags") %> to the html, it now autocompletes the textbox with System.Collections.Generic.List`1[Foo.Models.Tag]. Firstly, it's a string lazy list and not one of my other custom Tag classes. How can i fix this?Dwt
Is this solution now out of date with the current MVC RC2?Vassili
DefaultValueProvider does not exist anymore since RC, the alternative is changing the ValueProvider that comes with the controller that is just a IDictionary<string, ValueProviderResult>. See: forums.asp.net/t/1382242.aspxKatha

© 2022 - 2024 — McMap. All rights reserved.