I have several dropdownlists in a form. Each time the user selects a value in one of these dropdownlist do I want the value to be saved to the backend (database). I don't want to page to reload so I guess the best way to achive this is with ajax, and this is what I need help with.
How would I go about to get it to automaticly post the value to the server side when I select a value in a dropdownlist. Should I make 1 form for each of the drop down lists so I can update them individually? How do I get it to post the value as a ajax call, and not with a page reload? I'm using JQuery and JQuery mobile ontop of ASP MVC.
For demonstration purpose let me make show some code as it would be now: ViewModel:
public class ColorViewModel
{
public ColorViewModel()
{
Options = new List<string>(){ "red", "blue", "green" };
}
public string Value { get; set; }
public List<string> Options { get; set; }
}
View:
@model IEnumerable<ColorViewModel>
@using (Html.BeginForm())
{
foreach(var item in Model)
{
Html.DropDownListFor(m => m.Value, Model.Options)
}
<input type="submit" value="Save">
}
I want to remove the submit button from the form and do all of the submiting of the form when the user selects a value (I guess this can be achived by using javascript)
By default MVC should render id="Value"
for this field (you can override it in HTML params of helper method).
Then using jquery (if you are using MVC project template you already should have it in the project) you can post your form:
$(function() {
$('#Value').change(function() {
this.form.submit();
});
});