jquery - ASP.NET MVC 2 使用 jQuery 加载部分 View - 无客户端验证

标签 jquery asp.net-mvc validation asp.net-mvc-2 partial-views

我正在使用 jQuery.load() 来渲染部分 View 。这部分看起来像这样:

$('#sizeAddHolder').load(
                '/MyController/MyAction', function () { ... });

我的 Controller 中的操作代码如下:

    public ActionResult MyAction(byte id)
    {
        var model = new MyModel
        {
            ObjectProp1 = "Some text"
        };

        return View(model);
    }

    [HttpPost]
    public ActionResult MyAction(byte id, FormCollection form)
    {
        // TODO: DB insert logic goes here

        var result = ...;

        return Json(result);
    }

我返回的部分 View 如下所示:

<% using (Html.BeginForm("MyAction", "MyController")) {%>
    <%= Html.ValidationSummary(true) %>

    <h3>Create my object</h3>

    <fieldset>
        <legend>Fields</legend>

        <div class="editor-label">
            <%= Html.LabelFor(model => model.ObjectProp1) %>
        </div>
        <div class="editor-field">
            <%= Html.TextBoxFor(model => model.Size.ObjectProp1) %>
            <%= Html.ValidationMessageFor(model => model.ObjectProp1) %>
        </div>

        div class="editor-label">
            <%= Html.LabelFor(model => model.ObjectProp2) %>
        </div>
        <div class="editor-field">
            <%= Html.TextBoxFor(model => model.ObjectProp2) %>
            <%= Html.ValidationMessageFor(model => model.ObjectProp2) %>
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>

<% } %>

客户端验证在这种情况下不起作用。此外,包含验证消息的脚本也不包含在返回的 View 中。我的模型类中的两个属性都有 RequiredStringLength 属性。 有什么方法可以在这样加载的 View 中触发客户端验证吗?

最佳答案

首先,您应该返回部分 View 而不是 View 。

return PartialView(model);

其次,您是否尝试使用 AJAX 加载此部分 View ?在这种情况下,您可能需要使用 jquery.ajax

function ajax_update(path)
  $.ajax {
    url: path,
    success: function(result) {
      $('#sizeAddHolder').html(result);
    }
  return false;
}

关于jquery - ASP.NET MVC 2 使用 jQuery 加载部分 View - 无客户端验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2652586/

相关文章:

javascript - 悬停时水平滚动只运行一次?

jquery - 如何使用 jquery 将选定行中的标签加粗?

javascript - 粘性滚动菜单在 offset().bottom - 500 时隐藏

asp.net-mvc - mvc3中的十进制错误-该值对于字段无效

javascript - jQuery 单一选择器与 .find()

c# - : caching through HttpContext. Current.Cache 或静态缓存哪个更好?

c# - 是否有使用 AutoMapper 的 ValueResolver 映射 EF 实体的 EntityKey 值的通用方法?

validation - Camel 验证错误消息

c++ - boost program_options 自定义验证

ruby-on-rails - 验证 Ruby on Rails 中的 url 格式