【问题标题】:ASP.NET MVC Remote Attribute doesn't work in bootstrap modalASP.NET MVC 远程属性在引导模式下不起作用
【发布时间】:2016-03-20 08:56:48
【问题描述】:

我有使用引导模式的 CRUD 控制器。我有实体 Town,我想实现 TownName 属性是唯一的。所以我使用 Remote 属性:

public class Town
{
    ...
    [Required]
    [Remote("IsTownValid", "Town"]         
    public string TownName { get; set; }
    ...
}

在控制器中我有:

public JsonResult IsTownValid(string townName)
{
    return IsTownExist(townName) ? Json(false, JsonRequestBehavior.AllowGet) : Json(true, JsonRequestBehavior.AllowGet);
}

private bool IsTownExist(string townName)
{
    // repository-unitOfWork that get town with specified town name
    var town = repository.TownRepository.Get(filter: t => t.TownName == townName).SingleOrDefault();

    if (String.IsNullOrEmpty(townName))
        return true;
    else if (town != null)
        return true;
    else
        return false; 
}

我在 _Layout 视图中注册了 Microsoft jQuery Unobtrusive Validation 库。

问题是当我启动创建城镇的模式时,模式忽略远程属性。因此,出于测试目的,我在该控制器标准中创建创建页面和远程验证工作完美。所以,我的问题是为什么不在模态中工作?

建议,请...在此先感谢...

【问题讨论】:

  • 可能是因为模态正在动态加载而您没有重新解析验证器?旁注:它可以只是Json(!IsTownExist(townName), JsonRequestBehavior.AllowGet);
  • 您可能还想再次查看IsTownExist() 方法中的逻辑。 if (String.IsNullOrEmpty(townName)) { return true; } 应该在您调用数据库之前。

标签: c# asp.net asp.net-mvc twitter-bootstrap


【解决方案1】:

Stephen Muecke,感谢您的回答,因为他们引导我回答。这是我的激活模式的 JavaScript 代码。我评论了我添加到在模态中激活客户端验证的代码中的行:

$(function () {
    $.ajaxSetup({ cache: false });

    $("a[data-modal]").on("click", function (e) {

        $('#m-town-modal-content').load(this.href, function () {
            // this is the first add
            $.validator.unobtrusive.parse($('form'));

            $('#m-town-modal').modal({
                keyboard: true
            }, 'show');

            bindForm(this);
        });       

        return false;
    });
});

function bindForm(dialog) {
    $('form', dialog).submit(function () {
        // this is the second addition
        if(this.valid()) {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {               
                    if (result.success) {
                        $('#m-town-modal').modal('hide');                    
                        location.reload();
                    } else {
                        $('#m-town-modal-content').html(result);
                        bindForm();
                    }
                }
            });
            return false;
        }            
    });
}    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    相关资源
    最近更新 更多