Как проверить вход вне модели в MVC5 - PullRequest
0 голосов
/ 24 февраля 2020

Я пытался проверить ввод, который не соответствует модели. У меня есть следующий код:

@using (Html.BeginForm("Address", "Locations", FormMethod.Post, new { id = 
"mainForm" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })

<div class="card shadow-sm">
    <div class="card-header">
        <h3 class="card-title">
            Step 1
        </h3>
        <label>
            Search for service location(s)
        </label>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-4">
                <div class="form-group">
                    <label for="exampleInputEmail1">Zip code: <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="ZipCode" name="ZipCode" autocomplete="off" autofocus />
                    @Html.ValidationMessage("ZipCode")

                </div>
            </div>
            <div class="col-md-4">
                <div class="form-group">
                    <label for="exampleInputPassword1">House number:</label>
                    <input type="text" class="form-control" id="HouseNumber" name="HouseNumber" />
                </div>
            </div>
            <div class="col-md-4">
                <div class="form-group">
                    <label for="exampleInputPassword1">City:</label>
                    <input type="text" class="form-control" id="City" name="City" />
                </div>
            </div>
        </div>
    </div>
    <div class="card-footer">
        <div class="row">
            <div class="col-md-12">
                <button class="btn btn-primary" type="submit">
                    <i class="fas fa-search"></i>
                    Search for location(s)
                </button>
            </div>
        </div>
    </div>
</div>
}

Режим:

@model PagedList.IPagedList<iCRM.Models.Address>

Но имя, которое я дал для ввода, отсутствует в модели. Однако проверка не работает вообще. И ПОЧТА игнорирует мою проверку.

Может кто-нибудь мне помочь, что я делаю не так?

Заранее спасибо.

1 Ответ

0 голосов
/ 24 февраля 2020

У вас есть 2 варианта.

  1. добавить ZipCode в класс модели iCRM.Models.Address.

  2. Написать пользовательскую проверку с помощью обработчика Request.Forms ["ZipCode"] и Javascript на стороне клиента. (@ Html .ValidationMessage ("ZipCode") вы не можете вызвать)

Это идея, основанная на варианте 2, но не конкретный ответ.

Контроллер

    [HttpGet]
    public ActionResult Address()
    {


        return View();
    }

    [HttpPost]
    public ActionResult Address(AddressModel model)
    {
        if (String.IsNullOrEmpty(Request.Form["ZipCode"]))
        {
            ViewBag.ValidationForZipCode = "Problem with ZipCode";
        }

        return View();
    }

Вид

@model WebApplication1.Models.AddressModel

@{
ViewBag.Title = "Address";

string strValidationForZipCode = "";

if (ViewBag.ValidationForZipCode != null)
{
    strValidationForZipCode = ViewBag.ValidationForZipCode.ToString();
}
}

<h2>Address</h2>

@using (Html.BeginForm())
{
@Html.AntiForgeryToken(); 

<div class="form-horizontal">
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <div class="form-group">
        <div class="pull-right">
            <input type="submit" value="Create" class="btn btn-primary" />
        </div>
    </div>
    <table>
        <tr>
            <td>
                <div class="form-group">
                    @Html.LabelFor(model => model.Address1, htmlAttributes: new { 
 @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Address1, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Address1, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    <label for="exampleInputEmail1">Zip code: <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="ZipCode" name="ZipCode" autocomplete="off" autofocus />
                    <input type="hidden" id="hdValidationForZipCode" name="hdValidationForZipCode" value="@strValidationForZipCode" />
                </div>
            </td>
        </tr>
        <tr>
            <td>

            </td>
        </tr>
    </table>
</div>
}
<script type="text/javascript">
var str1 = document.getElementById("hdValidationForZipCode").value; //$('#hdValidationForZipCode').val();

if (str1 != "")
    alert(str1);
</script>

Модель

using System.ComponentModel.DataAnnotations;

namespace WebApplication1.Models
{
public class AddressModel
{
    [Required]
    public string Address1 { get; set; }

    public string Address2 { get; set; }
    public string City { get; set; }
    public string Country { get; set; }


}
}
...