2016-11-26 70 views
0

我有一個需要通過Ajax回發的應用程序。撥打ActionMethod時出現問題。下面是代碼。使用ajax調用動作方法時的問題contentType

控制器:

[HttpGet] 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    public JsonResult AjaxTest(object name) 
    { 
     return Json("Welcome" + name, JsonRequestBehavior.AllowGet); 
    } 

Cstml:

<form name="frmTest" method="POST"> 
@Html.Label("Your name Please") 
@Html.TextBox("username") 
<input class="btn btn-success btn-lg btn-block" type="submit" value="Login"> 

JQuery的:

$(function() { 
    $("form[name='frmTest']").submit(function (e) { 
     var name = $('#username').val(); 
     $.ajax(
     { 
      type: "POST", 
      //contentType: "application/json; charset=utf-8", 
      url: "MyTest/AjaxTest", 
      dataType: "json", 
      data: { name:name }, 
      success: function (data, status) { 
       alert("Pass"+data); 
      }, 
      error: function() { 
       alert("Fail"); 
      } 
     }); 
    }); 

}); 

通過使用命中AjaxTest與上面的代碼中斷點參數。當我使用contentType: "application/json; charset=utf-8",時,頁面回發沒有達到中斷點。 但這兩種情況下我都得到了失敗警報。無法找到問題,

+0

請問爲什麼你要一直到服務器來簡單地將「Welcome」添加到名稱? – CodingYoshi

+0

你正在嘗試提交表單時發送一些Ajax,我認爲這是一個或其他,而不是在同一時間。 –

+0

@CodingYoshi thnx,這是我的主應用程序的演示應用程序 – madan

回答

1

我不知道你在做什麼,但是因爲在你說的一個註釋中你將會把東西保存到數據庫中,通常在ASP MVC中它會這樣做。

爲使用AJAX發佈的任何內容創建一個類。例如,在這個例子中,我創建了一個名爲Person

public class Person 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
} 

類然後在你的表格,你可以有這樣的事情:

@{ 
    ViewBag.Title = "Test"; 
} 

<form name="frmTest" method="POST"> 
    @Html.Label("Your name Please") 
    @Html.TextBox("username") 
    <input class="btn btn-success btn-lg btn-block" type="submit" value="Login"> 
</form> 

<script> 
    $(function() { 
     $("form[name='frmTest']").submit(function (e) { 
      var name = $('#username').val(); 
      $.ajax(
      { 
       type: "POST", 
       //contentType: "application/json; charset=utf-8", 
       url: "AjaxTest", 
       dataType: "json", 
       data: { "Age": 55, "Name": name }, 
       success: function (data, status) { 
        alert("Pass" + data); 
       }, 
       error: function (ex) { 
        alert("Fail" + ex); 
       } 
      }); 
     }); 
    }); 

</script> 

然後讓該JSON將被提交給一個動作。對於上面的動作將會是這樣的:

public JsonResult AjaxTest(Person person) 
{ 
    return Json("Welcome" + person.Name, JsonRequestBehavior.AllowGet); 
} 

ASP MVC將照顧你的綁定。另請注意,我發佈的網址是「AjaxTest」,它將發佈到服務該表單的控制器的AjaxTest操作方法。

如果您有像下面這樣的控制器,那麼以上所有方法都可以使用。

public class AccountController : Controller 
{ 
    // This returns the view with the form 
    public ActionResult Test() 
    { 
     return View(); 
    } 
    public JsonResult AjaxTest(Person person) 
    { 
     return Json("Welcome" + person.Name, JsonRequestBehavior.AllowGet); 
    } 
} 
+0

你的意思是它按照你的異常工作嗎?你的意思是期望嗎?是的,e.preventDefault將停止提交表單是默認行爲 – CodingYoshi

+0

抱歉期望* – madan