ASP.NET MVC 2 使用 jQuery 加载部分视图 - 没有客户端验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2652586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:58:11  来源:igfitidea点击:

ASP.NET MVC 2 loading partial view using jQuery - no client side validation

jqueryasp.net-mvcvalidationasp.net-mvc-2partial-views

提问by Maksymilian Majer

I am using jQuery.load()to render a partial view. This part looks like this:

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

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

The code for actions in my controller is the following:

我的控制器中的操作代码如下:

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

I am returning a partial view that looks something like this:

我正在返回一个看起来像这样的部分视图:

<% 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>

<% } %>

Client side validation does not work in this case. What is more the script that contains validation messages also isn't included in the view that's returned. Both properties in my model class have Requiredand StringLengthattributes. Is there any way to trigger client side validation in a view which has been loaded like this?

在这种情况下,客户端验证不起作用。更重要的是,包含验证消息的脚本也不包含在返回的视图中。我的模型类中的两个属性都具有RequiredStringLength属性。有没有办法在这样加载的视图中触发客户端验证?

回答by Flexo

First of all you should return a partial view and not a view.

首先,您应该返回局部视图而不是视图。

return PartialView(model);

Second, are you trying to load this partial view with AJAX? In that case you might want to use jquery.ajax

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

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

回答by Rafael Mueller

You should use dataType on the ajax call

您应该在 ajax 调用中使用 dataType

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

From jQuery docs:

来自jQuery 文档

dataType Default: Intelligent Guess (xml, json, script, or html)

dataType 默认值:智能猜测(xml、json、脚本或 html)

The type of data that you're expecting back from the server. If none is specified, jQuery will intelligently try to get the results, based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

您期望从服务器返回的数据类型。如果没有指定,jQuery 将根据响应的 MIME 类型智能地尝试获取结果(XML MIME 类型将产生 XML,在 1.4 中 JSON 将产生一个 JavaScript 对象,在 1.4 脚本中将执行脚本,以及任何否则将作为字符串返回)。可用类型(以及作为第一个参数传递给成功回调的结果)是:

* "xml": Returns a XML document that can be processed via jQuery.
* "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
* "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching unless option "cache" is used. Note: This will turn POSTs into GETs for remote-domain requests.
* "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
* "jsonp": Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback.
* "text": A plain text string.

回答by tpeczek

I'm not sure if you are still loking for answer to your question, but I have write a post about making AJAX loaded forms work with client-side validation in ASP.NET MVC 2: http://tpeczek.com/2010/04/making-aspnet-mvc-2-client-side.html

我不确定您是否仍在寻找问题的答案,但我写了一篇关于使 AJAX 加载的表单与 ASP.NET MVC 2 中的客户端验证一起工作的帖子:http: //tpeczek.com/2010/ 04/making-aspnet-mvc-2-client-side.html

回答by jcruz

The problem is that the form loaded with ajax never gets registered with the Microsoft validation. To solve it call the following function Sys.Mvc.FormContext._Application_Load.

问题是使用 ajax 加载的表单永远不会在 Microsoft 验证中注册。要解决它,请调用以下函数 Sys.Mvc.FormContext._Application_Load。

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

That should fix it. Also, make sure that the forms you load via ajax have unique id's. Otherwise, the validation will fail.

那应该解决它。此外,请确保您通过 ajax 加载的表单具有唯一的 ID。否则,验证将失败。

Avoid using load(). It removes any scripts loaded in the response.

避免使用 load()。它删除响应中加载的所有脚本。

回答by user800534

In the html file you can have something like:

在 html 文件中,您可以包含以下内容:

sorry about that but I don't no how post a link html. So you can have a link class="delete", id= valueand a href= "javascript:;"

抱歉,但我不知道如何发布链接 html。所以你可以有一个链接="delete", id= value和一个href= "javascript:;"

Then I used this function to render a partial view:

然后我用这个函数来渲染一个局部视图:

 $(".delete").click(function(event){
          var id = $(".select").attr("id");
          var id2 = event.target.id;
          $.ajax({
                url: "Persona/Delete?idPersona=" + id2.toString(),
                success: function (data) {
                    $("#popUpConfirmar").html(data);
                }
            });

            dialogoPopUp.dialog("open");
        });

Remember in the controler you must have a action like:

请记住,在控制器中,您必须执行以下操作:

    public PartialViewResult Delete(int idPersona)
    {
        PersonaDataAccess personaDataAccess = new PersonaDataAccess();
        Persona persona = personaDataAccess.GetOne(idPersona);
        return PartialView("Delete",persona);
    }