Reputation: 33691
I have a webpage to submit a recipe. There are 5 fields for ingredients. If the recipe needs more than 5 ingredients, there is a button to 'add another ingredient' and some java script loads another ingredient input for them to use.
I'm not sure how to POST this data properly to my backend which is MVC4/C#.
Could I give them all the same id=ingredient and collect them as a string ingrdient[]? or whats the best practice to get form inputs when the number of inputs can change?
Thanks.
Upvotes: 0
Views: 1071
Reputation: 1469
Ok here is a sample: You can use this approach:
<div class="editor-field">
<input type="text" name="MyModelArray[0].Sugar" value="" />
<input type="text" name="MyModelArray[1].Tea" value="" />
<input type="text" name="MyModelArray[0].Sugar" value="" />
<input type="text" name="MyModelArray[1].Tea" value=""/>
</div>
<p>
<input type="submit" value="Create" />
</p>
Now you can get this in your controller using :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(List<Ingredient> MyModelArray) //Put a breakpoint here to see
{
return View();
}
[HttpPost]
public ActionResult About(List<string> MyStringArray) //Use this if you don't want a model
{
return View();
}
}
public class Ingredient
{
public string Sugar { get; set; }
public string Tea { get; set; }
}
}
Upvotes: 3
Reputation: 63956
I don't know exactly what's the best approach as far as MVC4 is concerned but you could definitely give all the inputs the same name and after submission, you should be able to retrieve them on the server side by just looking at the HttpContext.Request.Params
object.
Upvotes: 0
Reputation: 699
If you will give the same name with squared brackets, you should able to reach them as array when you submit the form.
<input type="text" name="data[]" value="">
Upvotes: 3