ASP.Net MVC Update ViewModel on DropDown Selection changed

点点圈 提交于 2019-11-30 21:03:48

From the comments, you want to be able to update labels based on the selected language. In order to do this you will need to use ajax to post the selected language to a controller method that return json and update the DOM. Your view model should be

public SelectList AvailableLanguages { get; set; }
public int SelectedLanguage { get; set; }

and in the controller

public ActionResult YourMethod()
{
  var model = new yourModel();
  model.SelectedLanguage = // set this if you want a default
  var availableLanguages = // get you list of languages
  model.AvailableLanguages = new SelectList(availableLanguages, "ID", "LanguageText")
  return View(model);
}

View

@Html.DropDownListFor(m => m.SelectedLanguage, Model.AvailableLanguages)

<script>
  var url = '@Url.Action("GetLanguageLabels", "yourControllerName")';
  $('#SelectedLanguage').change() {
    $.getJSON(url, { ID: $(this).val() }, function(response) {
      // Note you will need to give your labels an id attribute
      $('#Label1').text(response.Label1);
      $('#Label2').text(response.Label2);
    })
  });
</script>

And the method to get the labels based on the selected language

public JsonResult GetLanguageLabels(int ID)
{
  // Build a object of label values based on the selected language ID
  var data = new
  {
    Label1 = someValue,
    Label2 = anotherValue,
    ....
  };
  return Json(data, JsonRequestBehavior.AllowGet);
}

Side note: Some issues with your current code. (1) Your models have fields only, not properties (no get/set) so nothing would be bound on post back. (2) You cannot bind a html control to a complex object (only an value type, or in the case of <select multiple>, an array of value types).

You would make sure the elements are in a form and just and the name of the function after the onchange...

@onchange="submitdata();"

Then you would add the script.

function submitdata()
{
  $('form').submit();
}

For a more "MVC" approach you would start with a strongly typed view using a model.

@model My.Path.To.Model

You would also wrap the form data on your razor page with...

using (@Html.BeginForm("myMethod", "Home", FormMethod.Post)){
     //form and inputs here, ect
     <form method="POST" action="" >
         //properties bound to inputs to change your model, or html helpers like display for...
         <input type="Submit" name="Submit" value="Submit"/>
     </form>
}

You would then pass the model as a parameter in the Controller action, this is called on the submit of the form:

[HttpPost]
 public FileStreamResult myMethod(Model model)
 {
     string str = model.imapropertyonthemodel;

 }

If you are new to MVC I would recommend starting with the basics from W3 schools, or if you have pluralsight, there are some great tutorials there.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!