2017-10-09 64 views
0

我有一個簡單的Web應用程序,其中用戶輸入三個整數到表單中,並接收總和。在提交之前,表單結果是否隱藏?

我的問題是這樣的:我希望實際總和值不會出現,直到用戶已提交。意思是,當頁面打開時,ViewBag只顯示任何內容。提交後,將出現ViewBag內容。我可以用我現有的代碼來做到這一點嗎?

我知道這可能需要一個JavaScript函數。我只是沒有很多經驗將JS與C#集成在一起。

查看:

@{ 
ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 

<form action="" method="post"> 

Enter the 1st Number: <input id="firstInt" name="firstInt" type="text" value="0" /><br /> 
Enter the 2nd Number: <input id="secondInt" name="secondInt" type="text" value="0" /><br /> 
Enter the 3rd Number: <input id="thirdInt" name="thirdInt" type="text" value="0" /><br /> 

<input id="Submit" type="submit" value="submit" /> 
<input id="Reset" type="reset" value="reset" /><br /><br /> 
Sum = @ViewBag.result 
</form> 

控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index(int firstInt = 0, int secondInt = 0, int thirdInt = 0) 
    { 
     int sum = firstInt + secondInt + thirdInt; 
     ViewBag.result = sum; 
     return View(); 
    } 
} 
+0

您可以使用AJAX從JS調用的任何元素的控制器和設置和結果。如果您正在執行POST,請確保表單中的「action」屬性觸發器調用現有的操作方法名稱。 –

+1

我不會在這種情況下使用JS來隱藏和顯示。您可以修改您的C#視圖代碼,以僅響應POST顯示該行,或者在定義了「@ ViewBag.result」時僅顯示該行。如果您打算使用JS,那麼您將使用JS來完成整個計算,而不是將表單提交到Web服務器並獲取響應。 – nnnnnn

+0

'?使用jQuery,您可以實時更新'$('#sum')。val(...)'值,而不會顯示它。 –

回答