ASP.NET核心模型不与表单绑定 [英] Asp.net core model doesn't bind from form

查看:83
本文介绍了ASP.NET核心模型不与表单绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从第3侧静态页面(由Adobe Muse生成)中捕获发布请求,并通过MVC操作对其进行处理.

I catch post request from 3rd-side static page (generated by Adobe Muse) and handle it with MVC action.

<form method="post" enctype="multipart/form-data">
   <input type="text" name="Name">
   ...
</form>

针对空表单操作的路由:

Routing for empty form action:

app.UseMvc(routes => routes.MapRoute(
   name: "default",
   template: "{controller=Home}/{action=Index}"));

但是在相应的动作中,我有一个模型,每个属性都是空的

But in according action I have model with every property is empty

动作:

[HttpPost]
public void Index(EmailModel email)
{
   Debug.WriteLine("Sending email");
}

型号:

public class EmailModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Company { get; set; }
    public string Phone { get; set; }
    public string Additional { get; set; }
}

Request.Form具有来自表单的所有值,但模型为空

Request.Form has all values from form, but model is empty

[0] {[Name, Example]}
[1] {[Email, Example@example.com]}
[2] {[Company, Hello]}
[3] {[Phone, Hello]}
[4] {[Additional, Hello]}

推荐答案

请注意不要为动作参数指定与模型属性相同的名称,否则绑定器将尝试绑定到该参数而失败. >

Be careful not to give an action parameter a name that is the same as a model property or the binder will attempt to bind to the parameter and fail.

public async Task<IActionResult> Index( EmailModel email ){ ... }

public class EmailModel{ public string Email { get; set; } }

将操作参数电子邮件"更改为其他名称,它将按预期进行绑定.

Change the actions parameter 'email' to a different name and it will bind as expected.

public async Task<IActionResult> Index( EmailModel uniqueName ){ ... }

这篇关于ASP.NET核心模型不与表单绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆