At first I'm absolutely new on web development. I'm trying to develop a Web application which consists of a single page (I started with an empty project trying to follow the mvc pattern).
To populate my View I pass a ViewModel through my HomeController to my "Home"View.
Now I want to change a few Label-Texts depending on a DropDown selection.
ViewModel:
public IEnumerable<Models.Language> AvailableLanguages;
public Models.Language SelectedLanguage
Public IEnumerable<Models.Text> Content;
Language:
public int ID;
public string LanguageText;
Text:
public Language Language;
public string Description;
HTML: @model ViewModels.MyViewModel
<div>
@Html.DropDownFor(x => x.AvailableLanguages,
new SelectList(Model.AvailableLanguages,
"ID",
"LanguageText",
new {@onchange= ... }))
</div>
<div>
@{
@:@Model.MyViewModel.Content
.Where(o => o.Language.Equals(Model.SelectedLanguage)
.First())
.Description
}
</div>
I read something about this "@onchange" attribute (Ajax, JQuery) - but to be honest It'd be great if there would be any ASP/MVC/HTML solution to achive my goal - to update my SelectedLanguage Property everytime the selected item of the dropdown gets changed.
Additionaly: Is there a tutorial for webdevelopment (asp, html, ajax, jquery, js) you can recommend?
Thanx!
EDIT
Now I tried to implement the code provided but it seems that nothing happens when changing the selected item...
Script:
<div class="LanguageSelection">
@{
@Html.DropDownList("SelectedLanguage", new SelectList(Model.AvailableLanguages, "ID", "Description"))
<script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript">
var url = '@Url.Action("ChangeLanguage", "Home")';
$('#SelectedLanguage').change() {
$.getJSON(url, {
ID: $(this).val()
}, function(response){
$('#Title').text(response.Title);
});
};
</script>
}
</div>
JsonResult:
public JsonResult ChangeLanguage(int id) {
var data = new {
Title = HVM.Title.Where(o => o.Language.ID.Equals(id)).First(),
};
return Json(new { success = true });
}
The problem should be located somewhere in the script, the ChangeLanguage Method doesn't even get executed.
IEnumerable<Models.Language>). If your wanting to identify the selected language on post back, you need a property to bind to (sayint SelectedLanguage { get; set; }) and then@Html.DropDownFor(x => x.SelectedLanguage, new SelectList(Model.AvailableLanguages ...).MyViewModel.Contentwould only ever be the initial value of theSelectedLanguage. If your wanting to update something in the DOM based on the selected language, then you need to use ajax to call a controller, passing the selected language and returning the new new values you want to display. Note also your models only have fields (no get/set) so nothing will bind when you post back.int,stringetc), but not to a complex object (a<select>posts back a single value and has no concept of whatIEnumerable<Language>is. If you explain what it is you want to do (i.e. what is the purpose of handling the.changeevent), I can give you an answer.