How to Pass Jquery Variable Value to C# MVC

How to pass jQuery variable value to c# mvc?

You need to use jQuery.ajax() (or its shortened form jQuery.get()/jQuery.post()) with GET/POST method and set up a controller action with an argument to pass button ID:

jQuery (inside $(document).ready())

$('button').click(function () {
var btn = $(this).attr('id');
var url = '@Url.Action("ActionName", "ControllerName")';
var data = { id: btn };

// if controller method marked as POST, you need to use '$.post()'
$.get(url, data, function (result) {
// do something
if (result.status == "success") {
window.location = '@Url.Action("AnotherAction", "AnotherController")';
}
});
});

Controller action

[HttpGet]
public ActionResult ActionName(string id)
{
// do something
return Json(new { status = "success", buttonID = id }, JsonRequestBehavior.AllowGet);
}

[HttpGet]
public ActionResult AnotherAction()
{
// do something
return View(model);
}

If you want to pass retrieved button ID from AJAX into other action method, you can utilize TempData or Session to do that.

Asp.net pass jQuery variable to C# function

Add an Ajax call to your click event that does a POST/GET back to your MVC action, something like this:

                $.ajax({
async: false,
cache: false,
url: '@Url.Action("MyAction", "MyController")',
type: 'GET',
dataType: 'json',
data: myJsonString }
);

Your action would only return json (or a partial view, depending on the return type)

    [HttpGet]
public JsonResult MyAction()
{

string result = [some model data]

var json = Json(result, JsonRequestBehavior.AllowGet);
return json;

}

Pass parameter from MVC view to an action using jQuery

To pass query parameters (value for your action), you will have to use something like this:


var url = '@Url.Action("Selection", "Home", new { value = "inputValue" })';

It will generate following url: /Selection/Home?value=inputValue

How to pass a javascript variable to Razor c# code?

You cannot use a javascript variable in your c# code. But the reverse is possible. However in this scenario you must use ajax itself to load your partial view.

What you can try is ..

1) Create a ActionResult which will return a partial view. (Make sure you set the ActionResult name same as your partial view name, This is only to reduce confusion in your code.)

2) Then in jquery hit this ActionResult.

something like..

 $.get('/YourController/'+ JavaScriptVariable +'/',function(result){
//you got the partial view here...
$('#yourDiv').append(result);
});

Trying to pass a variable to Jquery from Razor

Its happening because U only append select without its option inside you Jquery. I recommend using AJAX and partial view to achieve ur goal.
First, separate the rendering of dropdownlist into another cshtml, for example the name is Institute.cshtml

Institute.cshtml

@model xxxx.Model.Institute //model would be your institute
<select style="padding-left: 5px; width: 100%;" class="BasicInfoFormControl" onblur="" name="restrictedInstitute[]" id="selectRestricted" />
<option value="0">Please Select</option>
@foreach (var item in Model)
{
if (@item.TradingName != null && @item.TradingName != " " && @item.TradingName != "")
{
<option value="@item.TradingName">@item.TradingName</option>
}
}
</select>

Then you call it as partialview in your HTML

<div class="col-md-3 input_fields_wrap">
@Html.Partial("Institute", Model.Institute)
<div class="row">
<div class="col-md-12 BasicInfoFormRow ">
<button class="add_field_button addMore">+Add More institutes</button>
</div>
</div>
</div>

And add the partialview in your Controller

xxController

PartialViewResult Institute()
{
return PartialView();
}

This is the first step to separate your dropdownlist into another partialView
The second step is calling an ajax in your add click button, and fetch the result using this partialView

javascript

$(document).ready(function () {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID

var x = 1; //initlal text box count
$(add_button).click(function{ //on add input button click
if (x < max_fields) { //max input box allowed
x++; //text box increment
$.ajax({
url: '@Url.Action("AddDropdown", "YourController")',
type: "GET",
success: function (result) {
$(wrapper).append(result);
}
});
}
});

$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});

this Javascript means, when u click Add button, you will request to your controller using Ajax. Then the controller will help you to render the dropdownlist and send the result back to your Client.
So, you need to add another function in your controller to receive this Ajax request

xxController

public ActionResult AddDropdown()
{
Model.Institute Result = new Model.Institute()
//you can generate your Model.Institue in here

Return PartialView("Institute", Result); //this will render Result with Institute.cshtml
}

after this, you can add dropdownlist into your html with the click add button

Passing Jquery variable to MVC Controller using AJAX

why dont use json format?

$(document).on("click", ".getDetails", function (e) {
var val = $(this).val();
alert(val);
$.ajax({
url: '/Home/GetDetails',
contentType: 'application/json',
type: 'POST',
data: JSON.stringify({"partsId": val}),
dataType: 'json'
})
.success(function (result) {
$('#detailsPlace').html(result);
})
.error(function (xhr, status) {
alert(status);
});
})


Related Topics



Leave a reply



Submit