2つのボタン(「First」と「Second」)と1つの非表示フィールドを持つビューがあります。ユーザーが「First」ボタンをクリックすると、最初のボタンの「data-myAttribute」属性の値として非表示フィールドが設定されます。ユーザーが「2番目」ボタンをクリックすると、2番目のボタンの「data-myAttribute」属性の値として隠しフィールドが設定されます。隠しフィールドが設定されたら、フォームを提出する必要があります。これは次のコードでうまくいきます。さらに、私はコントローラ内の隠しフィールドの値を見ることができる必要があります。コントローラの価値をどうやって得るのですか?ASP.NET MVC3 RAZOR:コントローラの非表示フィールド属性値の取得(ViewModelを使用)
namespace MyHiddenFieldTest.Controllers
{
public class ElementController : Controller
{
public class MyViewModel
{
public string ControlName { get; set; }
}
// GET:
public ActionResult MyElement()
{
MyViewModel myViewModel = new MyViewModel();
return View(myViewModel);
}
// POST:
[HttpPost]
public ActionResult MyElement(MyViewModel theViewModel)
{
string selectedControl = theViewModel.ControlName;
return View(theViewModel);
}
}
}
VIEW
@model MyHiddenFieldTest.Controllers.ElementController.MyViewModel
@{
ViewBag.Title = "MyElement";
}
<h2>MyElement</h2>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript">
$(document).ready(function()
{
$('#mainDiv input[type="button"]').on('click', function()
{
$('#from').val($(this).attr('data-myAttribute'));
alert($('#from').val());
$(this).closest('form').submit();
});
});
</script>
@using (Html.BeginForm())
{
<div id="mainDiv">
<input type="button" value="First" data-myAttribute="theFirst" />
<input type="button" value="Second" data-myAttribute="theSecond" />
<input type="hidden" id="from" value="1" />
<input type="hidden" id="to" value="2" />
</div>
}
READING
なぜ「-1」があるのだろうと思っています。しかし、私はあなたの意見を表現する自由を尊重します。他の質問やこのフォーラムには適していない質問があれば教えてください。 – Lijo