Asp.net pass jQuery variable to C# function - c#

I have go this code inside my razor view in Asp.Net:
#section MyScripts {
<script type="text/javascript">
$("button").click(function () {
var myVariable = this.id;
#{
var Line1 = "Software";
var Gruppe2 = Model.Where(x => x.Line1 == "Software").GroupBy(v => v.Line2).ToList();
}
});
</script>
}
As you can see, the myVariable receives the id via jQuery from the "button click event".
So lets say that the variable value is "Software".
How can I pass this variable to the c# code inside the jQuery?

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;
}

Related

Pass Model and Variables with AJAX

A partial view (_AddItem.cshtml) is called from the main view (Category.cshtml) in order to add existing items to the page on load.
I'm now adding AJAX so that an item can be added, to the page, by the user at the click of a button. When the form is subsequently submitted the item will be added to the model.
The partial view relies on the category model (activeCategoryModel) and two variables. Currently, these are successfully being passed from the view in the following way:
Category.cshtml
#Html.Partial(
"_AddItem",
activeCategoryModel,
new ViewDataDictionary(ViewData) { { "itemIndex", itemIndex }, { "itemLabel", itemLabel } }
);
My question is how can I pass the model (activeCategory) and these two variables when using AJAX? Below is the code I've started writing for the AJAX post:
Button and inputs added to view (Category.cshtml)
<input id="add-item-label" type="text" />
<input id="nextItemIndex" type="hidden" value="#activeCategoryModel.Items.Count" />
<button id="add-item" type="button">Add Item</button>
AJAX post added in javascript
This is not necessary fully functional code, I've just attempted to write an AJAX post with the variables in the 'data' parameter.
$("#add-item").click(function () {
var itemIndex = $("#nextItemIndex").val();
var itemLabel = $("#add-item-label").val();
$.ajax({
type: "POST",
url: '#Url.Action("_AddItem")',
data: '{{itemIndex: ' + itemIndex + '}, {itemLabel: ' + itemLabel + '}}',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
$("#nextItemIndex").val($("#nextItemIndex").val() + 1);
},
error: function () {
alert("Error while adding item");
}
});
return false;
});
Partial view call added to Controller
I think this is where the model and variables need to be included in the partial view call.
public ActionResult _AddItem(string itemIndex, string itemLabel)
{
return PartialView();
}
Partial View (_AddItem.cshtml)
This has not been changed for the AJAX post.
#model CategoryModel
#{ int i = (int)ViewData["itemIndex"];}
#{ string l = (string)ViewData["itemLabel"];}
...
There are different ways in this case,
Example : Html.RenderPartial directly rendered partial action without ajax.
If you want to use Ajax to call partialView , you must be render
Html. Because PartialView returned Html.
I think the most important value in Ajax request is dataType and
the second important point is added returned html data in a div element
jQuery("#add-item").click(function () {
var dItemIndex = 1; //$("#nextItemIndex").val();
var dItemLabel = "Text"; // $("#add-item-label").val();
$.ajax({
type: "POST",
url: '#Url.Action("_AddItem","Home")',
data: { itemIndex: dItemIndex, itemLabel: dItemLabel },
dataType: "html",
//contentType: "application/json; charset=utf-8",
success: function (d) {
console.log("Success");
$("#partialData").html(d);
**// Create div in cshtml Page
// <div id="partialData"></div>**
},
error: function () {
alert("Error while adding item");
}
});
return false;
});
At the controller side you can read parameters and fill in the content and send the PartialView as follows.
public ActionResult _AddItem(string itemIndex, string itemLabel)
{
ViewData["itemIndex"] = itemIndex;
ViewData["itemLabel"] = itemLabel;
return PartialView(new CategoryModel { Id = 5, Text = "Sample 5" });
}

How to pass data to ajax function with json?

I need to get an id from the URL , comment value from textbox, save it to database and show on page with ajax.
Im not sure how should look correct syntax in my controller and ajax function.
Controller
[HttpPost]
public JsonResult AddComment(int id, string comment)
{
if (ModelState.IsValid)
{
return Json(true); // what should be here
}
return Json(true);
}
Ajax
$('#submit').click(function () {
$.ajax({
url: '/Form/AddComment',
method: 'POST',
data: {
id: 4, //how to get id from url?
comment: 'test' //how to get textbox value?
},
success: function (data) {
console.log(data)
},
error: function (a, b, c) {
console.log('err')
}
})
});
this just show me that it work but i dont know how to move forward
Based upon your requirement, you would have to do the appropriate form handling at client side in order to get your variables like id and comment. You can use strongly typed model binding to get your form values and process them on submit or you can use JavaScript techniques to process your form variables. To extract out id from a URL, you can use a Regular Expression or other JavaScript string parsing techniques. I am giving you a simple example of getting your id from a URL and comment from a text box using JavaScript:
Your input control would look like:
<input type="text" id="commentBox" name="Comment" class="form-control" />
In order to achieve your desired functionality using AJAX to POST your form variables to controller, refer to the following code snippet:
AJAX:
<script type="text/javascript">
var url = 'http://www.example.com/4'; //Example URL string
var yourid = url.substring(url.lastIndexOf('/') + 1);
var yourcomment= document.getElementById('commentBox').value;
var json = {
id: yourid, //4
comment: yourcomment
};
$('#submit').click(function (){
$.ajax({
url: '#Url.Action("AddComment", "Form")',
type: "POST",
dataType: "json",
data: { "json": JSON.stringify(json)},
success: function (data) {
console.log(data)
},
error: function (data) {
console.log('err')
},
});
};
</script>
And you can get your values in your Controller like this:
using System.Web.Script.Serialization;
[HttpPost]
public JsonResult AddComment(string json)
{
if (ModelState.IsValid)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
string id= jsondata["id"];
string comment=jsondata["comment"];
// Do something here with your variables.
}
return Json(true);
}
My solution looks like this:
controller:
[HttpPost]
public JsonResult AddComment(int id_usr,string comment)
{
if (ModelState.IsValid)
{
Comments kom = new Comments();
kom.DateComment = DateTime.Now;
kom.Id_usr = id_usr;
kom.Comment = comment;
db.Comments.Add(kom);
db.SaveChanges();
return Json(kom);
}
return Json(null);
}
View
var url = window.location.pathname;
var idurl = url.substring(url.lastIndexOf('/') + 1);
$('#submit').click(function () {
console.log('click')
$.ajax({
url: '/form/AddComment',
method: 'POST',
data: {
comment: $("#Comments_Comment").val(),
id_usr: idurl,
},
success: function (data) {
console.log(data),
thank you all for guiding me to the solution

MVC drop down list onchange pass the selected value to the function in the controller and execute it

i am a new in using MVC3 Razor syntax and i have a view that containing a dropdownlist and i want when the user change the value of it , a function in the controller that take selected value as a parameter will be executed automatically.
this is the code that i wrote in the view and i have a compilation error in that line at runtime:
#Html.DropDownList("DONOR_BLOOD_GROUPE_ID", "--Select--", new {onchange="FilterdIndex(this.value)"})
"DONOR_BLOOD_GROUPE_ID" is in the viewBag and this is the function in the controller that i want to call .
public ViewResult FilterdIndex(int id)
{
var donor = db.DONOR.Include(d => d.BLOOD_GROUP);
var DONOR_BLOOD_GROUPE_ID = from BG in db.BLOOD_GROUP
select new
{
BG.GROUP_ID,BG.GROUP_NAME,
Checked=(BG.GROUP_ID==id)
};
ViewBag.DONOR_BLOOD_GROUPE_ID = DONOR_BLOOD_GROUPE_ID;
return View(donor.ToList());
}
this is javascript code it executes the controller function correctly but i don't know why after returning to the view i have the error msg in this line :
DONOR_BLOOD_GROUPE.error = function () { alert("Error in Getting States!!"); };
and this is the whole function:
<script src="~/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-1.7.1.js" type="text/javascript"></script>
$(document).ready(function () {
$("#DONOR_BLOOD_GROUPE_ID").change(function () {
if ($("#DONOR_BLOOD_GROUPE_ID").val() != "Select") {
var DONOR_BLOOD_GROUPE = {};
DONOR_BLOOD_GROUPE.url = '#Url.Action("FilterdIndex", "DONOR")';
DONOR_BLOOD_GROUPE.type = "POST";
DONOR_BLOOD_GROUPE.data = JSON.stringify({ id: $("#DONOR_BLOOD_GROUPE_ID").val() });
DONOR_BLOOD_GROUPE.datatype = "html";
DONOR_BLOOD_GROUPE.contentType = "application/json";
DONOR_BLOOD_GROUPE.error = function () { alert("Error in Getting States!!"); };
$.ajax(DONOR_BLOOD_GROUPE);
}
});
});
</script>
and this is the line that causes the exception in "DONOR[dynamic]" file
<select AutoPostBack="True" id="DONOR_BLOOD_GROUPE_ID" name="DONOR_BLOOD_GROUPE_ID" onchange="FilterdIndex(this.value)"><option value="">--Select--</option>
I assume you come from a WebForms background where this sort of thing happens all the time with 'Events' this sadly is not how MVC works.
To do what you are trying to do, you will need to create a jquery method for the onchange event of that drop down, then do an async post to your controller.
Have a look at this tutorial which should point you in the right direction
http://www.c-sharpcorner.com/UploadFile/4b0136/working-with-dropdownlist-in-mvc-5/
Hi Asmaa Rashad you can try using this way and your action Method which you are calling using Ajax must be of type JsonResult.
<script type="text/javascript">
$(document).ready(function () {
$("#DONOR_BLOOD_GROUPE_ID").change(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("FilterdIndex", "DONOR")',
dataType: 'json',
data: { id: $("#DONOR_BLOOD_GROUPE_ID").val() },
success: function (data) {
},
error: function (ex) {
alert('Failed to retrieve + ex);
}
});
return false;
})
});
</script>
For reference you can check this blog creating-simple-cascading-dropdownlist-in-mvc-4-using-razor

Get url parameters

Here is what I am trying to do. I'm trying to pass the drop down selected value to my controller.
I have a drop down menu like this:
#Html.DropDownList("divs", null, "--Select--", new {id="divs", onchange="SelectedIndexChanged(this.value);" })
#section Scripts
{
<script>
function SelectedIndexChanged(divs) {
document.getElementById('divs').href =
'/Controllers/MyFunction?divs=' + divs;
}
</script>
}
in my controller, I am trying to get the value divs:
public MyFunction (string divs)
{
string type = Request.QueryString["divs"];
MessageBox.Show(type); //this is empty
}
Typing this from my head compiler so it might not be quite right but should get you closer.
#Html.DropDownList("divs", null, "--Select--", new { id="divs"})
#section Scripts
{
<script>
$(function() {
$("#divs").change(function() {
val selected = $(this).find(":selected").val();
$.ajax({
type: 'POST',
url: '#Url.Action("MyFunction", "Controller", new { divs = selected })',
dataType: 'json',
});
});
});
</script>
}
In your controller:
public ActionResult MyFunction (string divs)
{
...
}
I believe that this is what you're trying to do. It's not a complete solution, you have to work it out.
Note: I'm using jQuery for the javascript part.
Action:
public JsonResult MyFunction (string divs)
{
return Json(divs, JsonRequestBehavior.AllowGet);
}
View:
$(function() {
$("#divs").changed(function() {
$.ajax({
url: '/controllers/myfunction'
, cache: false
, type: 'GET'
, dataType: 'json'
, data: { divs = $(this).val() }
}).done(function (data) {
alert(data);
});
});
});
You can remove that javascript binding from the dropdown declaration.

Making an Ajax call to a partial view after ajax success

I have a partial view that contains all my buttons and it needs to display updated values after a form is submitted. At the submission I already have it rendering another partial view, is there a way to make it work where on success of that one being rendered it re-renders. Here is the code I am trying to get to work now based on what I've seen in other places.
jQuery in my view:
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$('#ChangeGrade').click(function (e) {
var tdata = $('#form1').serialize();
var origname = $('#HeatGradeDiv').find('input[name="grade"]').first().val();
var newname = $('#HeatGradeDiv').find('input[name="updatedGrade"]').first().val();
var heatname = $('#HeatGradeDiv').find('input[name="hiddenHeat"]').first().val();
$.ajax({
type: "POST",
data: {
mCollection: tdata,
grade: origname,
updatedGrade: newname,
hiddenHeat: heatname
},
url: '#Url.Action("ChangeGrade","Home")',
success: function (result) { success(result); }
});
});
function success(result) {
$('#HeatGradeDiv').dialog('close');
$("#Partial_Chem_Analysis").html(result);
//ajax call I'm trying to get working
$.ajax({
type: "POST",
url: "/Home/ButtonsPartial",
success: function (result2) { $("#ButtonsPartial").html(result2); }
});
}
});
</script>
Here is the controller method I'm calling. When I run it now it is not getting hit.
public ActionResult ButtonsPartial()
{
ButtonsModel B = new ButtonsModel();
B.GetData(searchQ);
return PartialView(B);
}
Any help is appreciated.
If you attach it to a debugger such as (chrome developer tools or firebug) are you seeing any http or js errors?
It looks like you might need to make it a GET rather than POST...
$.ajax({
type: "GET",
url: "/Home/ButtonsPartial",
success: function (result2) { $("#ButtonsPartial").html(result2); }
});

Categories

Resources