자 홈 컨트롤러와 동작 인덱스가 있습니다. 내보기는 홈 컨트롤러의 데모 기능에서 값을 가져옵니다. 인덱스 뷰에서 버튼을 누르면 (자) homecontroller 객체가 생성되고 ID가 생성됩니다. 1로 초기화됩니다. 따라서 데모 기능의 두 번째 조건은 실행되지 않습니다. 그러나 id 변수를 정적으로 설정하면 작동합니다. 그래서 버튼 클릭시마다 컨트롤러 객체가 매번 생성됩니다. 왜 그런가요? 특정 객체에 대해 유사한 작업을 수행 할 때마다 다른 객체를 생성해야 할 필요성이 있습니까?MVC : 액션을 수행 할 때마다 컨트롤러 객체가 생성되는 이유는 무엇입니까?
홈 컨트롤러 :
public class homeController : Controller
{
//
// GET: /home/
public ActionResult Index()
{
return View();
}
public int id = 1;
public string demo()
{
if (id == 1)
{
id++;
return "hello";
}
id--;
return "";
}
}
색인보기 :
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$('document').ready(function() {
$('#b1').click(function() {
var URL = "/home/demo";
$.get(URL, function (data) {
$("#t1").html(data);
});
});
});
</script>
<div>
<p id="t1"></p>
<input id="b1" type="button" value="button1" />
</div>