Environment:
ASP.NET Core MVC 3.1 and Library .NET Standard
Goals:
-
Create object from DLL (dll can be changed at any moment) with no constant structure, ex. class Obj{ int, string, string}, but another dll will has class Obj {int, int, int}.
-
Pass this object to view.
-
Generate single "form box" without knowing what properties have object. ex. string => textbox, bool => checkbox etc.
-
Pass this data to method/controller/api.
My problem:
On that moment I can first three points, but I can't pass data to the Controller. I tried debug it, but method Index(int x, int y) always is call with params x = 0, y = 0.
Code:
HomeController.cs
[HttpGet]
public IActionResult Index()
{
Assembly dllAssembly = Assembly.LoadFile(Environment.CurrentDirectory +
"\\TestLib.dll");
Type dllType = dllAssembly.GetType("TestLib.TestModel");
tempObj = Activator.CreateInstance(dllType);
ViewBag.Message = tempObj;
return View();
}
[HttpPost]
public IActionResult Index(int x, int y)
{
Assembly dllAssembly = Assembly.LoadFile(Environment.CurrentDirectory +
"\\TestLib.dll");
Type dllType = dllAssembly.GetType("TestLib.TestModel");
tempObj = Activator.CreateInstance(dllType);
dllType.GetProperty("X").SetValue(tempObj, x);
dllType.GetProperty("Y").SetValue(tempObj, y);
ViewBag.Message = tempObj;
return View();
}
TestModel.cs
public class TestModel
{
[Range(0, 10)]
public int X { get; set; }
[Range(0, 10)]
public int Y { get; set; }
}
Index.cshtml
@{
ViewData["Title"] = "Home Page";
var data = ViewBag.Message;
}
@using (@Html.BeginForm())
{
@Html.EditorFor(model => data)
<input type="submit" />
}
Generated html
<form action="/" method="post">
<div class="editor-label">
<label for="data_X">X</label>
</div>
<div class="editor-field">
<input class="text-box single-line" data-val="true" data-val-range="The field X must be between 0 and 10." data-val-range-max="10" data-val-range-min="0" data-val-required="The X field is required." id="data_X" name="data.X" type="number" value="0">
<span class="field-validation-valid" data-valmsg-for="data.X" data-valmsg-replace="true"></span>
</div>
<div class="editor-label">
<label for="data_Y">Y</label>
</div>
<div class="editor-field"><input class="text-box single-line" data-val="true" data-val-range="The field Y must be between 0 and 10." data-val-range-max="10" data-val-range-min="0" data-val-required="The Y field is required." id="data_Y" name="data.Y" type="number" value="0">
<span class="field-validation-valid" data-valmsg-for="data.Y" data-valmsg-replace="true"></span>
</div>
<input type="submit">
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8Aif0fO55UxKoguBNLmuYLdNU-SzXiXyGEcaohb3AphnylgsdCg_Dq-J4el3v_tf5lWzTHB6aF-ifu7rVNpXroUk6TrBVj1hn9T4cSgwankNmSXjyWiIoE-UHDwl_LVBL4SL6vmdJLnPDOAFOv2cip4">
</form>
Aucun commentaire:
Enregistrer un commentaire