Привязка модели бритвенных страниц к названию модели и без нее - PullRequest
0 голосов
/ 27 апреля 2020

У меня есть ASP. NET 2.0 Страница бритвы, предназначенная для реализации контактной формы. Вот часть файла Contact.cs html:

@page
@model ContactModel
<form method="post">
    <input type="text" asp-for="ContactMessageModel.Name" />
    <input type="email" asp-for="ContactMessageModel.Email" />
    <input type="text" asp-for="ContactMessageModel.Message" />
    <div class="g-recaptcha" data-sitekey="<SiteKey>"></div>
    <button type="submit" class="btn btn-primary">Send</button>
</form>

Вот часть файла Contact.cs html .cs:

public class ContactModel : PageModel
{
    [BindProperty]
    public ContactMessageModel ContactMessageModel { get; set; }

    public IActionResult OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        return RedirectToPage("MessageSent");
    }
}

public class ContactMessageModel
{
    [Required]
    public string Name { get; set; }

    [Required]
    public string Email { get; set; }

    [Required]
    public string Message { get; set; }

    [Required, BindProperty(name="g-recaptcha-response"]
    public string RecaptchaResponse { get; set; }
}

Когда форма после отправки в запросе отображаются следующие данные формы:

ContactMessageModel.Name: Fractor
ContactMessageModel.Email: fractor@example.com
ContactMessageModel.Message: Hi there!
g-recaptcha-response: <recaptcha response data>

Поскольку динамически создаваемое имя данных формы g-recaptcha-response не начинается с ContactMessageModel, привязываются только свойства Name, Email и Message.

Я рассмотрел использование [Bind(Prefix = "")], но похоже, что я не могу применить это к (одиночному) свойству в классе.

Есть ли способ привязки ко всем свойствам в этой модели класс, несмотря на разные префиксы?

1 Ответ

0 голосов
/ 28 апреля 2020

Редактировать

Вы можете создать a hidden control в представлении, чтобы связать RecaptchaResponse, и запустив событие data-callback робота, передав значение ответа скрытому элементу управления в js.

    <form method="post">
        <input type="text" asp-for="ContactMessageModel.Name" />
        <input type="email" asp-for="ContactMessageModel.Email" />
        <input type="text" asp-for="ContactMessageModel.Message" />
        <div class="g-recaptcha" data-sitekey="your key" data-callback="ClickRobot"></div>
        <input type="hidden" asp-for="ContactMessageModel.RecaptchaResponse" />
        <button type="submit" class="btn btn-primary">Send</button>
    </form>

<script src="https://www.google.com/recaptcha/api.js?hl=en-US"></script>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script>
    var ClickRobot = function () {
        var response = grecaptcha.getResponse();
        $("#ContactMessageModel_RecaptchaResponse").val(response);
    };
</script>

Контакт:

 public class ContactModel : PageModel
    {
        [BindProperty]
        public ContactMessageModel ContactMessageModel { get; set; }
        public IActionResult OnPostAsync()
        {  
            if (!ModelState.IsValid)
            {
                return Page();
            }

            return RedirectToPage("MessageSent");
        }
    }

    public class ContactMessageModel
    {
        [Required]
        public string Name { get; set; }

        [Required]
        public string Email { get; set; }

        [Required]
        public string Message { get; set; }

        [Required]
        public string RecaptchaResponse { get; set; }
    }

Вот процесс тестирования:

enter image description here

...