I'm facing a challenge in my HTML page where I need to pass a variable value from the frontend to a Model class in an MVC project.
What is the most efficient way to achieve this with minimal code?
Here's what I have attempted:
Index.cshtml:
var mana = document.getElementById("ID").value;
var MyAction = '@Url.Action("MyAction", "Home")';
$.ajax({
type: "POST",
url: MyAction,
data: { 'myVar': mana },
success: function (result) {
$('#ResultsDiv').html(result);
@{
var inventoryObj = Model.InventoryDataList.Where(x => x.ID == Int32.Parse(Model.grabTest)).Select(x => x.DAYOFWEEK);
var inventoryJson = new JavaScriptSerializer().Serialize(inventoryObj);
}
var inventoryRefined = JSON.parse('"@inventoryJson"');
var InventoryDataList = JSON.parse(htmlDecode(inventoryRefined));
console.log(InventoryDataList);
}
});
HomeController.cs:
public ActionResult MyAction(Models model, string myVar)
{
model.grabTest = myVar;
//My Action Code Here
return Json(true, JsonRequestBehavior.AllowGet);
}
Models.cs:
public string grabTest = "";
What is the end goal here?
My LINQ query requires a parameter (ID) to filter an object list. This ID value is coming from a JS variable which necessitates using ajax.
To fulfill this requirement, I decided to use ajax to send the JS variable to an action result and store it in a public variable within Models.cs.
The concept is simple, but I'm struggling with the implementation. Any suggestions?