MVC 1.0 Ajax.BeginForm()在Html.BeginForm()中提交

时间:2022-12-06 21:37:36

I have a View for creating a new account in my application. This view starts with Html.BeginForm() and hits the right controller (Create) no problems.

我有一个在我的应用程序中创建新帐户的视图。这个视图以Html.BeginForm()开始,并点击正确的控制器(创建)没有问题。

I decided to add an Ajax.BeginForm() so that I could make sure an account with the same name doesn't already exist in my application.

我决定添加一个Ajax.BeginForm(),这样我就可以确保在我的应用程序中不存在同名的帐户。

When I click the submit using either button it goes to the same controller (Create). To try and differentiate which submit button was clicked, I put in a check to see if the request is Ajax then try to run a different code path. But Request.IsAjaxRequest() doesn't fire. What is my best bet to implement this functionality in an existing form with MS Ajax?

当我使用任一按钮单击submit时,它将转到相同的控制器(Create)。为了尝试区分单击了哪个submit按钮,我进行了检查,看看请求是否是Ajax,然后尝试运行不同的代码路径。但是Request.IsAjaxRequest()不火。用MS Ajax实现这个功能的最佳方法是什么?

<% using (Html.BeginForm()) {%>
           ..............
  <% using(Ajax.BeginForm("Echo", 
     new AjaxOptions() { UpdateTargetId = "EchoTarget" })) 
  { %>    
     Echo the following text: 
  <%=Html.TextBox("echo", null, new { size = 40 })%>
  <input type="submit" value="Echo" />
  <% } %>   
  <div id="EchoTarget">

controller code:

控制器代码:

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(User newUser)
    {
        if (Request.IsAjaxRequest())
        {
            return Content("*you hit the ajax button");
        }
        else
        { //regular create code here.....
        }
  </div>

2 个解决方案

#1


2  

If you insist on multiple form usage..use Javascript in a some function like this

如果你坚持使用多种形式。在这样的函数中使用Javascript

<SCRIPT>
  function InnerFormSubmitter(dataForm, actionForm) {
  actionForm.innerHTML = dataForm.innerHTML;
  actionForm.submit();      
 }
</SCRIPT>

<form name="yourButton" action="ValidateSomething" method="post"></form>

<form name="mainForm" action="SavedData" method="post">
<input type="textbox" name="text1">
<input type="textbox" name="text2">
<button name="validateUserButton" id="FormButton" onChange=
"InnerFormSubmitter  (this.form, document.getElementById('yourButton'))">

</button>
  </form>

Hope this helps!

希望这可以帮助!

Addendum on jQuery usage for your scenario:

您的场景的jQuery用法的附录:

Since you wanted a link:

既然你想要链接:

<a href="javascript:isValidUser(<%=Model.USerId%>);">Check Availability</a>


function isValidUser(userId) { 
var url = "<CONTROLLER>/<ACTION>/" + userId; 
$.post(url, function(data) { 
    if (data) { 
        // callback to show valid user 
    } else { 
        // callback to show error/permission 
    } 
}); 
} 

And you controller should have:

控制器应该有:

[AcceptVerbs("POST")] 
public bool IsValidUser(int id) { 
 // check availability 
 bool allow = CheckUser(); 

 // if allow then insert 
 if (allow) { 
    //insert user

    return true; 
 } else { 
    return false; 
 } 
} 

Further Update on jQuery:

进一步更新jQuery:

Instead of

而不是

document.getElementById('UserIdent').value

you can use

您可以使用

$('#UserIdent').val();

Update on JSON usage

更新JSON使用

The JsonResult class should be used in the Controller and $.getJson function in the View.

应该在控制器和$中使用JsonResult类。在视图中调用getJson函数。

$(function() {
    $('#yourLinkOrButton').click(function() {
        $.getJSON("<CONTROLLER>/GetUserAvailability/", null, function(data) {
            $("#yourDivorLablel").<yourFunctionToUpdateDiv>(data);
        });
     });

  public JsonResult GetUserAvailability()
    {
        //do all validation and retrieval
        //return JsonResult type

    }

#2


2  

You cannot nest forms, ever, in any HTML page, no matter how you generate the form. It isn't valid HTML, and browsers may not handle it properly. You must make the forms siblings rather than children.

无论如何生成表单,都不能将表单嵌套到任何HTML页面中。它不是有效的HTML,浏览器可能不能正确地处理它。您必须使窗体成为兄弟姐妹,而不是子窗体。

#1


2  

If you insist on multiple form usage..use Javascript in a some function like this

如果你坚持使用多种形式。在这样的函数中使用Javascript

<SCRIPT>
  function InnerFormSubmitter(dataForm, actionForm) {
  actionForm.innerHTML = dataForm.innerHTML;
  actionForm.submit();      
 }
</SCRIPT>

<form name="yourButton" action="ValidateSomething" method="post"></form>

<form name="mainForm" action="SavedData" method="post">
<input type="textbox" name="text1">
<input type="textbox" name="text2">
<button name="validateUserButton" id="FormButton" onChange=
"InnerFormSubmitter  (this.form, document.getElementById('yourButton'))">

</button>
  </form>

Hope this helps!

希望这可以帮助!

Addendum on jQuery usage for your scenario:

您的场景的jQuery用法的附录:

Since you wanted a link:

既然你想要链接:

<a href="javascript:isValidUser(<%=Model.USerId%>);">Check Availability</a>


function isValidUser(userId) { 
var url = "<CONTROLLER>/<ACTION>/" + userId; 
$.post(url, function(data) { 
    if (data) { 
        // callback to show valid user 
    } else { 
        // callback to show error/permission 
    } 
}); 
} 

And you controller should have:

控制器应该有:

[AcceptVerbs("POST")] 
public bool IsValidUser(int id) { 
 // check availability 
 bool allow = CheckUser(); 

 // if allow then insert 
 if (allow) { 
    //insert user

    return true; 
 } else { 
    return false; 
 } 
} 

Further Update on jQuery:

进一步更新jQuery:

Instead of

而不是

document.getElementById('UserIdent').value

you can use

您可以使用

$('#UserIdent').val();

Update on JSON usage

更新JSON使用

The JsonResult class should be used in the Controller and $.getJson function in the View.

应该在控制器和$中使用JsonResult类。在视图中调用getJson函数。

$(function() {
    $('#yourLinkOrButton').click(function() {
        $.getJSON("<CONTROLLER>/GetUserAvailability/", null, function(data) {
            $("#yourDivorLablel").<yourFunctionToUpdateDiv>(data);
        });
     });

  public JsonResult GetUserAvailability()
    {
        //do all validation and retrieval
        //return JsonResult type

    }

#2


2  

You cannot nest forms, ever, in any HTML page, no matter how you generate the form. It isn't valid HTML, and browsers may not handle it properly. You must make the forms siblings rather than children.

无论如何生成表单,都不能将表单嵌套到任何HTML页面中。它不是有效的HTML,浏览器可能不能正确地处理它。您必须使窗体成为兄弟姐妹,而不是子窗体。