1

I want to let user add as many tag as he wants to an article, say I have these simple classes:

public class Tag
{
    public string Name { get; set; }
}

public class Article
{
    public List<Tag> Tags { get; set; }

    public Article()
    {
        Tags = new List<Tag>();
    }
}

And my controller looks like this:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new Article());
    }

    [HttpPost]
    public ActionResult Edit(List<Tag> tags)
    {            
        //tags is null here
        return View();
    }
}

In my view I just have a simple textbox with a link named "add", and a submit button. When the "add" is clicked, it calls a javascript function that will take the value entered and create a new disabled textbox with the value, this disabled textbox is then placed in a specified div. When submit, it posts to the Home/Edit. The "add" part works fine, user can add as many tags as necessary on the fly.

The problem is, when submitting, none of the newly created disabled textboxes were passed in as parameters, the tags parameter always is null. I've made sure the textboxes generated have the name of tags[0].Name, tags[1].Name, etc.

Is my only option to use $.ajax() or $.post()? I have a lot more textboxes and dropdowns to collect user input that I have not shown here, and creating json out of them to be used in $.ajax or $.post seems not very fun. I was hoping I can make use of the mvc model binding if possible.

Any help/suggestion is appreciated!

1 Answer 1

1

What you can do is build up the list in the javascript memory for the page.

So you create a Tag object in the memory like

var tag= new {Name=$('input-selector').val()};

and then push it into an object as follows:

tagList.push(tag);

When you are done with adding all the tags what you can do is make an ajax call to the server as follows:

$.ajax(
url:url,
data: {tag=$.toJSON(tagList)},
type: "POST",
dataType: "json",
success: function () {}

)

and now you should be able to use the List object with the required data at the server.

let me know if that works out for you.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks I think I might have to go this route, but I am still puzzled why those value cannot bind to asp.net mvc, hmmm..
it would be nice if you could up vote and/or mark this as the answer. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.