Home > database >  Is there a way to access the ViewModel object from the controller?
Is there a way to access the ViewModel object from the controller?

Time:02-21

Is there a way to refer to the view model's binded object (from the controller) after performing an ajax request to the controller? I'm trying to access the view model object's properties that are updated inside of the .cshtml file after the user updates the input fields and clicks on "Submit", so I know what data to pass to an external API.

I started passing some of the properties using the query string way through the ajax request (amountEur: @Model.AmountEUR), but haven't been able to find out if possible to access (some cached form of?) the view model object from the controller directly

Index.cshtml

<h1>Converter</h1>

<div >
    <div >
        <form>
             <div >
                Amount in EUR: 
                @Html.TextBoxFor(m => m.AmountEUR);
                @Html.ListBoxFor(x => x.SelectedCurrencyTypes, Model.CurrencyTypes, new { style="width:200px; display:block; margin-top:1vh;" } )
             </div>
             <button id="convertBtn"  type="button">Convert</button>
             <p id="data"></p>
        </form>
    </div>
</div>

@section Scripts{
    <script>
        $('#convertBtn').click(function () {
            var url = "/Home/QueryFixerAPI";
            $.get(url, { amountEur: @Model.AmountEUR,  }, function (data) {
                $("#data").html(data);
            });
        })
    </script>
}

View model class:

public class HomeIndexViewModel
{
    public float AmountEUR { get; set; }
    public List<SelectListItem> CurrencyTypes { get; set; }
    public List<string> SelectedCurrencyTypes { get; set; }
    public Dictionary<string, float> Rates { get; set; }
}

Relevant home controller methods:

public ActionResult Index()
{
    HomeIndexViewModel homeIndexViewModel = new HomeIndexViewModel
    {
        SelectedCurrencyTypes = new List<string>(),
        CurrencyTypes = GetCurrencyTypes()
    };

    return View(homeIndexViewModel);
}

public async Task<JsonResult> QueryFixerAPI(float amountEUR)
{
    string url = $"{baseUrl}/{DateTime.Now.ToString("yyyy-MM-dd")}?access_key={accessKey}&base=EUR&symbols=USD,CAD,ILS";

    using (HttpClient client = new HttpClient())
    {
        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new 
            MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = await client.GetAsync(url);

        if (response.IsSuccessStatusCode)
        {
            var data = await response.Content.ReadAsStringAsync();
            var serializer = new JavaScriptSerializer();
            Root obj = serializer.Deserialize<Root>(data);

            return Json(data, JsonRequestBehavior.AllowGet);
        }
    }

    return null;
}

CodePudding user response:

.NET MVC uses HTTP which is stateless hence you can't access form data that isn't passed to the controller. You will need to include all properties you need in your ajax request;

var data = {
   amountEur: @Model.AmountEUR,
   CurrencyTypes:{
      ...
   },
   SelectedCurrencyTypes:{
      ...
   },
   Rates:{
      ...
   }
};

$.get(url, data, function (data) {
   $("#data").html(data);
});

Then in your controller, you specify that the data is bound to the type you want;

public async Task<JsonResult> QueryFixerAPI(HomeIndexViewModel viewModel)
{
   var test = viewModel.amountEur;
   ...
}
  • Related