2011-12-11 9 views
1

我正在努力解決一些我甚至無法確定的問題。如何在.NET MVC 3中只觸發一個沒有控制器處理請求的JavaScript函數Razor

我在.NET MVC 3 Razor項目中有一個典型的表單頁面。在這個頁面中是一個帶有搜索機制的Google地圖。搜索包含一個調用JavaScript函數以在找到位置時更新地圖的表單。

當我嘗試使用它時,視圖的控制器處理請求,並且控制器的模型狀態無效(因爲用戶尚未完成表單的其餘部分)。結果是重置地圖的頁面的表示(完全與我之後的相反)。

這裏的視圖的簡化版本:

@model OnlineEventReporting.ViewModels.ReportShortViewData 
@{ 
    Layout = "~/Views/Shared/_LayoutGoogleMap_with_all_js_code.cshtml"; 
}  
<script type="text/javascript"> 
    function showAddress(address) { [processing code] } 
</script> 

@using (Html.BeginForm("Index", "ShortReport", FormMethod.Post, new { name = "shortForm", id = "shortForm", data_ajax = "false" })) 
    { 
    @Html.ValidationSummary(true) 

    Info for the controller to handle: 
     @Html.TextBoxFor(model => model.AddressDetail.Street1, new { @maxlength = "50" }) 

    <!-- I want this to 'fire' the JavaScript 'showAddress' function and for the controller to ignore it --> 

    <form style="text-align:center" action="#" onsubmit="showAddress(this.address.value); return false"> 
     <input type="text" size="20" id="address" name="address" value="North Street, Guildford" /> 
     <input type="submit" value="Search!" /> 
    </form> 

    <div id="map" style="width: 100%; height: 400px; margin-left:20px;"></div> 

    More info for the controller to handle: 
     @Html.TextBoxFor(model => model.AddressDetail.Street2, new { @maxlength = "50" }) 

    } 

我知道我有一個表格內的形式在這裏,但我不是我怎麼回事,可能接近這個,因爲我需要的地圖和搜索功能右我的主要形式的中間。

任何幫助將不勝感激。

非常感謝,

Chris。

+1

你不能在HTML中嵌套窗體。 – Oded

回答

0

您的代碼會生成無效的HTML - 嵌套表單不是有效的HTML。

問題是,input type="submit"可能會導致提交最頂端的表單而不是您所期望的。

爲什麼不能有一個正常的按鈕,並將該功能附加到點擊事件?

+0

非常感謝。是的,我確實嘗試過,但我在其他地方遇到過問題,這讓我覺得它不起作用 - 我認爲Google API一定會有一些事情發生。 事實上,我在其他地方有一個錯誤。這完美的作品!非常感謝。 – ChrisCurrie

0

你在找什麼是一個AJAX請求。您的控制器仍然會處理請求。但是,它會異步執行,沒有完整的回發。

首先,擺脫嵌套窗體標籤,你不需要它。相反,試試這個:

Info for the controller to handle: 
     @Html.TextBoxFor(model => model.AddressDetail.Street1, new { @maxlength = "50" }) 

    <!-- I want this to 'fire' the JavaScript 'showAddress' function and for the controller to ignore it --> 

     <input type="text" size="20" id="address" name="address" value="North Street, Guildford" /> 
     <input type="submit" value="Search!" onclick="showAddress(this.address.value); return false;" /> 

    <div id="map" style="width: 100%; height: 400px; margin-left:20px;"></div> 
+0

非常感謝您的幫助。 – ChrisCurrie

相關問題