Not sure what I'm missing in my code. I have a view with a few radio buttons and want to render a different partial view when a radio button is selected. Here is my code:
Controller
public ActionResult Method(string value)
{
var pv = "";
switch (value)
{
case "radio1":
pv = "_XPartial";
break;
case "radio2":
pv = "_YPartial";
break;
case "radio3":
pv = "_ZPartial";
break;
}
return PartialView(pv);
}
View div to render partialview
<div id"="renderarea">
#*Render partialview here.*#
</div>
JavaScript
$(document).ready(function () { GetPartial(); });
$("input[name='RadioOptions']").on('change', function () { GetPartial(); })
function GetPartial() {
var selection = $("input[name='RadioOptions']:checked").val();
//alert(selection) -- THIS ALERT SHOWS THE CORRECT VALUE
$.ajax({
url: '#Url.Action("Method", "Home")',
data: {'value' : selection},
contentType: 'application/html',
type: 'GET',
dataType: 'html',
success: function (pv) {
//alert(pv) -- THIS ALERT SHOWS THE HOLE PARTIAL VIEW HTML CODE
$("#renderarea").html(pv); -- THIS HERE ISN'T WORKING
}
});
}
The part that seems to not be working is $("#renderarea").html(pv); and I really don't know why. Have someone had this issue before?
Try this, it should be work:
$.ajax({
url: "/Home/Method",
data: selection,
type: 'GET',
dataType: 'html',
success: function (pv) {
$("#renderarea").html(pv);
}
});
Related
I'm a new developer asking my first SO question :). Working on a form that has some calculated fields based off corresponding text inputs in ASP.NET MVC. Essentially, takes value from text box, AJAX post that value to controller, perform calc, returns that data to read-only calculated field.
I have the following code for this working:
$("#volume").focusout(function () {
volume = $(this).val()
$.ajax({
type: "POST",
url: '/StaffingPlan/CalculatorAction',
data: { volume: volume },
dataType: "json",
success: function (data) {
console.log(data);
$("#selectorsNeeded").val(data);
}
});
});
$("#drops").focusout(function () {
drops = $(this).val()
$.ajax({
type: "POST",
url: '/StaffingPlan/CalculatorAction',
data: { drops: drops },
dataType: "json",
success: function (data) {
console.log(data);
$("#liftsNeeded").val(data);
}
});
});
and in the controller:
public ActionResult CalculatorAction(string volume, string drops)
{
int data = 0;
//one calculation performed for volume, but will be others to calculate
if (volume != null && volume != "")
{
data = Int32.Parse(volume) / 150 / 9;
}
//example of another calc
if (drops != null && drops != "")
{
data = Int32.Parse(drops) / 25 / 6;
}
return Json(data, JsonRequestBehavior.AllowGet);
}
This works, however, the form has several other inputs and calculated fields. Obviously there's better/dryer way to write this instead of duplicating the .focusout function. Would be nice to just get the field ID that changes and assign value to appropriate variable. Hope this makes sense! Any direction would be appreciated very much.
Change your code to this:
$("#volume").focusout(function () {
var data= { volume: $(this).val()},
var resultField= $("#selectorsNeeded");
calculateResult(data, resultField);
});
$("#drops").focusout(function () {
var data= { drops: $(this).val() },
var resultField= $("#liftsNeeded");
calculateResult(data, resultField);
});
function calculateResult (data, resultField) {
$.ajax({
type: "POST",
url: '/StaffingPlan/CalculatorAction',
data: data,
dataType: "json",
success: function (result) {
console.log(result);
resultField.val(result);
}
});
};
I have made a filtering method. This method is working like a charm and when I type something the table updates to the search string. This is my method for the search:
loadList() {
var searchString = $(".search-input").val();
$.post('/Translation/List?searchString=' + searchString, function (data) {
$(".table-content-view").html(data);
});
}
And when I wanna insert a new record I call this method:
saveTranslation() {
$.ajax({
url: '/Translation/Edit',
data: new FormData($(`${tr.selectedclass} #translation-form`)[0]),
processData: false,
contentType: false,
type: 'POST',
success: function (response) {
if (response.success === true) {
loadList();
}
}
});
}
This method works fine (confirmed with postman and chrome dev tools). The problem is I need to press F5 to see the new record instead that it refresh instantly. As you can see I call the method LoadList() to refresh the table but this doesn't work.
NOTE:
I use a partial view for the table.
This is my C# method for the list:
[HttpPost]
public async Task<IActionResult> List(string searchString)
{
var translations = _context.translation.AsQueryable();
translations = translations.OrderBy(x => x.CORETRANSLATIONID);
if (!String.IsNullOrEmpty(searchString))
{
translations = translations.Where(x => x.ORIGINAL.Contains(searchString));
}
return PartialView(await translations.ToListAsync());
}
Can someone point me in the right direction?
In my post method in JQuery I changed it too
saveTranslation() {
$.ajax({
url: '/Translation/Edit',
data: new FormData($(`${tr.selectedclass} #translation-form`)[0]),
processData: false,
contentType: false,
type: 'POST',
success: function (response) {
loadList();
}
});
}
The if statement was not necessary.
I have placed a bootstrap toggle switch in my application
Now i want is to send the On and Off values to my action method
Bellow is my razor syntax
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset style="height:60px">
<legend style="text-align:center; font-size:large; font-family:'Times New Roman'; background-color:#C8E6C9; color:red">Remote On/Off</legend>
<input id="test_id" name="cmdName" type="checkbox" checked data-toggle="toggle">
</fieldset>}
For passing data to controller from JS i have searched many articles and found that ajax is the way to do it
Bellow is my script for ajax inside JS
<script>
var cmdName = '#Session["cmdName"]';
$("#test_id").on("change", function (event) {
if ($(this).is(":checked")) {
$.ajax({
url: '#Url.Action("MultiGraph")',
type: 'Post',
data: 'On',
success: function () {
alert(data)
}
});
} else {
$.ajax({
url: '#Url.Action("MultiGraph")',
type: 'Post',
data: 'Off',
success: function () {
alert(data)
}
});
}
}); </script>
I have also used session variable but getting null value in it
Bellow is my controller code
public ActionResult MultiGraph(string search, string start_date, string End_date, string cmdName, int? page)
{
//search contain serial number(s)
//cmdName is for input checkbox
}
Bellow is the image for my switch button
When i switch it to Off then this Off string should be sent to my action method and vise versa
Updated Code
After reading comments i have done the following changes to my code
I have added a new action method of type Post
[HttpPost]
public ActionResult ToggleSwitch (string search, string cmdName)
{
List<SelectListItem> items = new List<SelectListItem>();
var dtt = db.ADS_Device_Data.Select(a => a.Device_Serial_Number).Distinct().ToList();
foreach (var item in dtt)
{
if (!string.IsNullOrEmpty(item))
{
items.Add(new SelectListItem { Text = item, Value = item });
}
}
ViewBag.search = items;
return View();
}
Bellow are changes in my razor
$("#test_id").on("change", function (event) {
if ($(this).is(":checked")) {
$.ajax({
url: '#Url.Action("ToggleSwitch")',
type: 'Post',
data: '{"cmdName": "On"}',
success: function () {
alert(data)
}
});
} else {
$.ajax({
url: '#Url.Action("ToggleSwitch")',
type: 'Post',
data: '{"cmdName": "Off"}',
success: function () {
alert(data)
}
});
}
});
But still i get no alert message, when i inspect element i found this error
I am stuck to this problem from almost 2 days
Any help would be appreciated
You need to use the $ character to invoque jQuery functions and pass your data from page to controller with the same name you defined in the action method using Json notation:
'{"cmdName": "On"}',
$.ajax({
url: '#Url.Action("ToggleSwitch")',
type: 'Post',
data: '{"cmdName": "On"}',
success: function () {
alert(data)
}
Furthermore, you might need to decorate your mvc action whith the [HttpPost] attribute.
I am attempting to use an AJAX call to render a partial view when a radio button is selected. I have searched and have tried what appears to be the best approach via comments on Stack. When I click the radio button, I have no result, in debug, I get a Status Code: 500 Internal Server Error? Any assistance would be great.
Partial View Names:
_BOA.cshtml
_TA.cshtml
_MNB.cshtml
View:
<td class="radio-inline">
#Html.RadioButton("bankSelect", "MNBConvert", false, new { #class = "radioMNB" }) MNB Conversion
#Html.RadioButton("bankSelect", "BOAConvert", false, new { #class = "radioBOA" }) BOA Conversion
#Html.RadioButton("bankSelect", "TAConvert", false, new { #class = "radioTA" }) TA Conversion
</td>
Javascript:
<script src="~/Scripts/jquery-1.9.0.js"></script>
<script type="text/javascript">
$(function () {
$("[name=bankSelect]").on('change', function () {
// var $radio = $(this);
var checked = $("input[name='bankSelect']:checked").val();
$.ajax({
url: '#Url.Action("GetBankToConvert", "Home")',
data: checked,
type: 'GET',
success: function (data) {
$("#renderPartialView").html(data);
}
});
});
});
</script>
Controller:
[HttpGet]
public ActionResult GetBankToConvert(string bankSelect)
{
if (bankSelect == "MNBConvert")
{
return PartialView("_MNB");
}
else if (bankSelect == "BOAConvert")
{
return PartialView("_BOA");
}
else
{
return PartialView("_TA");
}
}
You aren't sending a key/value pair as data, only a value.
Try
$.ajax({
url: '#Url.Action("GetBankToConvert", "Home")',
data: {bankSelect: checked },
type: 'GET',
success: function (data) {
$("#renderPartialView").html(data);
}
});
WHen in doubt, inspect the actual request in network tab of browser dev tools to see exactly what is sent and received among all the other components of a request
I have an MVC application with a controller named Angular (I use AngularJS as well), which has an action called GetQuestion. That action returns a JsonResult which looks like this (grabbed from Chrome):
{"game":{"Title":"Diablo III","ImgPaths":["d31.jpg","d32.jpg"]},"Answers":["Diablo III","World of Tanks","Need for Speed"]}
My JS function is like this:
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { alert(data); })
});
But instead of the Json I wrote above, alert window only says [object Object]
Update
Ok, that was fixed, thaks. However as you may suspect, my goal is not to present this data in alert box, but use it somehow. So here's my controller in Angular
function QuestionCtrl($scope) {
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: function (data) {
$scope.answers = JSON.stringify(data.Answers);
$scope.imgPath = JSON.stringify(data.game.ImgPaths[0]);
}
});
}
And then the view:
<div ng-controller="QuestionCtrl">
<img class="quizImage" src="~/Gallery/{{imgPath}}"/>
#using (Html.BeginForm("Answer", "Angular", FormMethod.Post))
{
<p ng-repeat="answer in answers"><input type="radio" name="game" value="{{answer}}"/> {{answer}}</p>
<p><input type="submit" value="Answer"/></p>
}
</div>
And I don't have neither image or the questions. If I hardcode them in controller then it's ok.
An alert will show that, i would suggest using console.log(data)
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { console.log(data); })
});
or as the comments states:
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { alert(JSON.stringify(data)); })
});
I resolved my second problem like this:
function QuestionCtrl($scope, $http) {
$http.post('/Angular/GetQuestion',null).success(function(data) {
$scope.answers = data.Answers;
$scope.imgPath = data.game.ImgPaths[0];
//console.log($scope.answers);
//console.log($scope.imgPath);
});
}
Note that it's AngularJS.
The reason it's happening is because JSON is an Object in JavaScript. When you type
alert(data);
It will attempt to cast the object to a string which in this case will only output that fact that it's an Object.
To view the contents of an object you can write a simple function to use with an alert or console.log.
function outputProperties(anObject) {
var props = '';
for (var prop in anObject) {
props += '\n' + prop + ' value: ' + anObject[prop];
}
return props;
}
And use it like this
alert(outputProperties(data));
For starters... when ever you are dynamically building the src url for an image (using the {{expression}} syntax from Angular) you need to not use the "src" attribute and use the "ng-src" angular directive. It allows angular time to process your url before the image is loaded.