ASP.NET MVC远程属性在引导模式中不起作用

时间:2016-03-20 08:56:49

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

我有使用Bootstrap模式的CRUD控制器。我有实体城镇,我想实现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库注册。

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

建议,请...提前致谢...

1 个答案:

答案 0 :(得分:0)

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;
        }            
    });
}