Reputation: 159
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!
Upvotes: 1
Views: 875
Reputation: 15579
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.
Upvotes: 1