如何将数据绑定到用户定义的类asp.net核心2



我定义了一个类似的模型

public class X { 
int a;
MyClass b;
}

我有一个动作看起来像这个

public IActionResult Test(X x){}

现在,当用户提交数据时,我想操作该数据,然后将其分配给b。我该怎么做?

您没有提供详细的解释,例如您希望如何提交数据,假设您有一个包含子Author属性的图书模型类:

public class Book
{
public int id { get; set; }
public string name { get; set; }
public Author author { get; set; }
}

public class Author {
public int authorId { get; set; }
public string authorName { get; set; }
}

在您看来,使用表单中的标记帮助程序,您可以绑定到Author.authorName:

@model Book
<form asp-controller="Home" asp-action="RegisterInput" method="post">
BookID:  <input asp-for="id" /> <br />
BookName: <input asp-for="name" /><br />
AuthorID:  <input asp-for="author.authorId" /> <br />
AuthorName: <input asp-for="author.authorName" /><br />
<button type="submit">Register</button>
</form>

在控制器中,您会发现输入值将自动绑定到相关属性:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RegisterInput(Book book)
{
return View();
}

最新更新