I'm pretty new regarding frontend, and couldn't find a clear solution to this simple problem. In a Visual 2017 c# ASP.NET Framework MVC project, for a single page with ONLY ONE SUBMIT button which is already used for updating some string of my model totalInfo, I want to update the integer property ModelltypeForView of my model from the selected value of n radiobuttons.
I learnt I could update my controller model going with an AJAX call, but I can't find the way to update my view model, I must miss something simple but not obvious for a beginner.
Here are the main parts of my MVC.
I am aware of the problems due to the return type of my SettModelltype of my controller, as well as the ajax and foreach loop of my view, so basically: how do I finish this code? Is this problem even fixable without any partial view?
Thank you so much for your time.
// Model TotalInfoModell.cs
public class TotalInfoModell
{
public List<Modelltype> Modelltyper { get; set; }
public int ModelltypeForView { get; set; }
}
public class Modelltype
{
public int MTIndex { get; set; }
public string MTName { get; set; }
public bool MTSelected { get; set; } //? useless?
}
// Controller MainController.cs
static TotalInfoModell _totalInfo;
[HttpGet]
public ActionResult Main()
{
if (_totalInfo == null)
{
_totalInfo = new TotalInfoModell();
}
return View(_totalInfo);
}
[HttpPost]
public ActionResult SettModelltype(TotalInfoModell totalInfoFraView)
{
_totalInfo.ModelltypeForView = totalInfoFraView.ModelltypeForView;
for (int i = 0; i < _totalInfo.Modelltyper.Count; i++)
{
_totalInfo.Modelltyper[i].MTSelected = (i == _totalInfo.ModelltypeForView);
} /// Could be useless
return RedirectToAction("Main"); //????
}
// View Main.cshtml
@foreach (var modelltype in Model.Modelltyper)
{
@Html.RadioButtonFor(i => modelltype.MTIndex == Model.ModelltypeForView, modelltype.MTIndex, new { @class = "MTSelected" }) // ????
@modelltype.MTName<br />
}
...
<script>
$(function () {
$('.MTSelected').change(function () {
var viewModel = {
"ModelltypeForView": $('.MTSelected:checked').val(),
};
$.ajax({
url: '@Url.Action("SettModelltype", "Main")',
data: viewModel,
type: 'POST',
success: function (data) {
},
error: function (xhr) {
alert("It didn't work");
}
}).done(function (data) {
alert("Done");
$('#Id').val(data.ModelltypeForView); //??? Should return totalInfoModell
});
});
});
</script>