I know how to post a list of objects to a form in ASP.NET, but suppose I want to post some other values at the same time?
Is there a way to have a form, like this
<form method="POST" action="test">
<input type="text" name="name" value="Roryok" />
<input type="text" name="email" value="<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f198959e9f85969887949e84859c88949c90989db19e879483859994989f859483df9f9485">[email protected]</a>" />
<input type="text" name="[0].hobby" value="dibbling" />
<input type="text" name="[0].level" value="amateur" />
<input type="text" name="[0].hobby" value="fargling" />
<input type="text" name="[0].level" value="intermediate" />
<input type="text" name="[2].hobby" value="garbling" />
<input type="text" name="[2].level" value="expert" />
</form>
Post to a method that looks something like this?
[HttpPost]
public ActionResult test(MyViewModel model){
/// do some stuff with the model here
return View();
}
public class MyViewModel{
public string name { get; set; }
public string email { get; set; }
public List<Hobby> hobbies { get; set; }
}
public class Hobby{
public string hobby { get; set; }
public string level { get; set; }
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Try this:
<form method="POST" action="test">
<input type="text" name="name" value="Roryok" />
<input type="text" name="email" value="<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5ccc1cacbd1c2ccd3c0cad0d1c8dcc0c8c4ccc9e5cad3c0d7d1cdc0cccbd1c0d78bcbc0d1">[email protected]</a>" />
<input type="text" name="hobbies[0].hobby" value="dibbling" />
<input type="text" name="hobbies[0].level" value="amateur" />
<input type="text" name="hobbies[1].hobby" value="fargling" />
<input type="text" name="hobbies[1].level" value="intermediate" />
<input type="text" name="hobbies[2].hobby" value="garbling" />
<input type="text" name="hobbies[2].level" value="expert" />
</form>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0