2013-12-16 100 views
0

Here is a picture of the error.在我對項目進行了一些更改後出現此錯誤。當你按下按鈕時,它應該去控制器記錄網站的用戶。我重新將我的佈局重新引導,並更改/刪除了屬於該網站的很多CSS。這可能是相關的,但不知道如何。這裏是按鈕的代碼:未捕獲TypeError:無法調用null的方法'submit'

@if (Request.IsAuthenticated) { 
    <text> 
     Hello, @Html.ActionLink(User.Identity.Name, "Manage", "Account", routeValues: null, htmlAttributes: new { @class = "username", title = "Manage" })! 
     @using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" })) { 
      @Html.AntiForgeryToken() 
      <a href="javascript:document.getElementById('logoutForm').submit()">Log off</a> 
     } 
    </text> 
} else { 
    <ul> 
     <li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li> 
     <li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li> 
    </ul> 
} 

有沒有人知道爲什麼會發生這種情況?

+2

'getElementById('logoutForm')'爲空,請檢查表單是否存在 – Marthijn

+1

使用視圖源來驗證您的註銷表單中的dos有已呈現的ID – rene

+0

@Marthijn @rene好像logoff isent是新版本,顯然是這樣的:http://i.imgur.com/hKBdtty.png。在我的舊版本中,我也在css文件中包含這行代碼:'#logoutForm {display:inline; }'。我應該閱讀CSS還是可以讓表單不存在? – JazzMaster

回答

1

我會假設你的問題是在這一行。

@using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" })) { 

檢查您的網頁源代碼,我會認爲您的操作在您的窗體上看起來像這樣。

action="Account/LogOff?id=logoutForm" 

解決方案:

@using (Html.BeginForm("LogOff", "Account", null, FormMethod.Post, new { id = "logoutForm" })) { 

這應該修復它爲你:)

更新:

可以切換碼左右,使其工作方式不同,但仍能正常工作。

選項1:

將其粘貼到佈局文件的末尾。

<script>$(function() { 
    $('#logoutForm a').on('click', function() { 
      $('#logoutForm').submit(); 
    }); 
</script> 

選項2:

更改標籤的

<button type="submit">Log Off</button> <!-- no JavaScript --> 

方案3:

<!-- I think this will work --> 
<a onclick="document.getElementById('logoutForm').submit()">Log Off</a> 

我個人比較喜歡選項2,因爲你只是用一個提交按鈕像你應該這樣做,而不是JavaScript。

更新#2:

@using(Html.BeginForm("LogOff", "Account", null, FormMethod.Post, new { id = "logoutForm" }) { 
    @Html.AntiForgeryToken() 
    <button type="submit">Log Out</button> 
} 

應該產生:

<form action="/Account/LogOff" method="POST" id="logoutForm"> 
    <input type="hidden" name="__RequestVerification" value="***" /> 
    <button type="submit">Log Out </button> 
</form> 

。注意到行動方法屬性。此外,請確保從代碼中刪除文本標籤,因爲它們旨在強制Razor語法接受它們之間的任何文本而不是Razor語法。

+1

你可以使用chrome工具「檢查頁面」並粘貼你獲得的表單標籤的html。只是表單標籤會有幫助。 –

+0

正如我在上述評論中所說的,註銷沒有任何形式。你可以看到它的外觀(舊版本),以及它現在的外觀(新版本):http://i.imgur.com/hKBdtty.png。 我已經截取了html的截圖,因爲它現在在表單中:http://i.imgur.com/lyKmYe8.png。我試過了你發佈的所有三種方法,但都沒有成功。唯一一個提供響應的是方法2,它刷新了網站並給出了一個包含請求驗證令牌的長url。其他2與以前一樣給出相同的錯誤「未捕獲的類型錯誤:無法調用方法'提交'null」。 – JazzMaster

相關問題