我有两个仅包含数据的类(设置和凭据)。 我不知道该如何称呼这些课程,所以请耐心等待。
数据类示例。
class Settings
{
public string Host { get; set; }
public int Port { get; set; }
}
class Credentials
{
public string UserName { get; set; }
public string Password { get; set; }
}
我想使用MVC控制器操作创建一个包含这两个数据类的新对象。
对象类的示例。
class Object
{
private readonly Settings _settings;
private readonly Credentials _credentials;
public Object(Settings settings, Credentials credentials)
{
_settings = settings;
_credentials = credentials;
}
}
我想做的事的例子。
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Create(Settings settings, Credentials credentials)
{
new Object(settings, credentials);
return View(Index());
}
}
我的问题我该如何实现呢?不必将每个参数都放在 IActionResult Create()方法中。
我的POST表单应该是什么样的?
谢谢。
答案 0 :(得分:1)
您几乎完全正确。我将使用的模型:
public class Settings
{
public string Host { get; set; }
public int Port { get; set; }
}
public class Credentials
{
public string UserName { get; set; }
public string Password { get; set; }
}
class Object
{
private readonly Settings _settings;
private readonly Credentials _credentials;
public Object(Settings settings, Credentials credentials)
{
_settings = settings;
_credentials = credentials;
}
}
public class ObjectView
{
public Settings Settings { get; set; }
public Credentials Credentials { get; set; }
}
控制器动作:
public IActionResult Index()
{
return View();
}
public IActionResult Create()
{
return View(new ObjectView());
}
[HttpPost]
public IActionResult Create(ObjectView objectView)
{
var obj = new Object(objectView.Settings, objectView.Credentials);
return RedirectToAction("Index");
}
用于创建模型的剃刀视图:
@model ObjectAsParametersInAction.Models.ObjectView
@{
ViewBag.Title = "View";
}
<h2>View</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ObjectView</h4>
@Html.LabelFor(m => m.Credentials.UserName)
@Html.EditorFor(m => m.Credentials.UserName)
@Html.LabelFor(m => m.Credentials.Password)
@Html.EditorFor(m => m.Credentials.Password)
@Html.LabelFor(m => m.Settings.Host)
@Html.EditorFor(m => m.Settings.Host)
@Html.LabelFor(m => m.Settings.Port)
@Html.EditorFor(m => m.Settings.Port)
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
请求中已过帐的表单数据将包含参数,例如:
Credentials.UserName=John&Credentials.Password=Unkown&Settings.Host=127.0.0.1&Settings.Port=80
在创建发布操作中,所有这些都将模型绑定到ObjectView公共属性。