How to Pass javascript variable to Controller in MVC from View
You could set up a hidden field in your form for the state (I assume state is a property on your RegisterModel?) and in your stateID.change function have it assigned the value to the hidden field for it to be passed on submit.
e.g:
Hidden field in the form can be set up with (inside your begin form code):
@Html.HiddenFor(model => model.StateID, new { id = hiddenStateID" })
Then your jQuery would be (untested, this is more pseduo code to give you the idea):
$(document).ready(function ()
{
$("#stateID").change(function (){
var state= $('#stateID :selected').text();
getCities(state);
$("#hiddenStateId").val(state);
});
});
Rahul
Updated on July 25, 2020Comments
-
Rahul almost 4 years
all I want to pass one javascript variable to Controller from MVC View from Form. This is my own selected text variable which I want to pass to controller so that I can retrieve and save in Database.Any help will be appreciated I am sharing the code which I want
View -->I am getting selected text value which I want to pass to controller
$(document).ready(function () { $("#stateID").change(function () { var state= $('#stateID :selected').text(); getCities(state); }); });
Now I want to pass this state variable to controller from an mvc form
@using (Html.BeginForm("Register", "Registration", FormMethod.Post)) { <input type="submit" value="Save" style="text-align:center" /> }
Now, this is my controller Code which I want to retrieve
[HttpPost] public ActionResult Register(RegisterModel Regmodel) { if (ModelState.IsValid) { return View(); } }
Thanks @Rondles My issue is resolved now and thank you guys for ur quick resonse
-
Zaki about 10 yearsuse ajax to call the controller and pass your parameters
-
Rahul about 10 years@zaki actually I don't want to go for Ajax because I have so may other controls also and through json I don't want to send ..
-
-
Rahul about 10 yearsCan You please share some sample code to achieve this
-
Rahul about 10 yearsHi @Rondles thanks for your code it worked for me and my issue is resolved ...really appreciate your quick response