ASP.NET MVC3 RAZOR: Retrieving Hidden field Attrib

2019-09-19 07:41发布

问题:

I have a view that has two buttons(“First” and “Second”) and one hidden field. When user clicks on “First” button, hidden field will be set as the value of “data-myAttribute” attribute in the first button. When user clicks on “Second” button, hidden field will be set as the value of “data-myAttribute” attribute in the second button. Once the hidden field is set, the form need to be submitted. This much is working fine with the following code. Further, I need to be able to see the value of the hidden field in the controller. How do we get the value in controller?

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. Passing JSON data from controller action to a razor view

回答1:

ASP.Net MVC automatically binds action parameters to form posts.
Just add a string from parameter to the action method.

However, you will also need to name="" the inputs in order for the browser to submit them.


Actually, however, your entire script is unnecessary.

Just write

<input type="submit" name="from" value="First" />
<input type="submit" name="from" value="Second" />

The browser will submit the name / value pair of whichever button was clicked.