Passing Object From Controller to JavaScript JQuery - c#

This is driving me crazy. All I'm trying to do is to pass in a Id to a ActionMethod which is working and have an Object be returned to the javascript. Then in javascript, I want to be able to say something like..Objec.Property, ie/ Student.Name, or Student.GPA.
Any help is appreciated. I tried json but couldn't get that to work either.
ActionResult:
[AcceptVerbs(HttpVerbs.Get)]
public Epic GetEpicPropertyDetails(int id)
{
var Epictemplist = epicRepository.Select().Where(x => x.Id.Equals(id));
return Epictemplist.SingleOrDefault();
}
javascript:
<script type="text/javascript">
$(document).ready(function () {
$(".ListBoxClass").click(function (event) {
var selectedid = $(this).find("option:selected").val();
event.preventDefault();
$.get("/Estimate/GetEpicPropertyDetails", { id: selectedid }, function (result) {
$(".TimeClass").val(result);
});
});
});
</script>
result.Name is obviously wrong I just dont know how to call this the right way.

Tman, I had a similiar issue that Darin helped me with. I needed to add a $.param to my getJSON. Check out this post MVC ListBox not passing data to Action

try changing your method like this
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetEpicPropertyDetails(int id)
{
var Epictemplist = epicRepository.Select().Where(x => x.Id.Equals(id)).SingleOrDefault();
return Json(Epictemplist, JsonRequestBehavior.AllowGet);
}
Than from your JS
<script type="text/javascript">
$(document).ready(function () {
$(".ListBoxClass").click(function (event) {
var selectedid = $(this).find("option:selected").val();
event.preventDefault();
$.get("/Estimate/GetEpicPropertyDetails", { id: selectedid }, function (result) {
$(".TimeClass").val(result.Name);
}, 'json');
});
});
</script>

Related

Making a post request and after submitting a form

I am having this problem while working on an eshop I am building, I want to simply do a post request to a controller (that is not returning a view) while also submiting a form.. I do not know what is wrong with this code
<script>
$(document).ready(function () {
console.log("sad");
$("a[data-form-method='post']").click(function (event) {
event.preventDefault();
var element = $(this);
var action = element.attr("href");
element.closest("form").each(function () {
var form = $("#form1");
form.attr("action", action);
form.submit();
});
});
});
</script>
Here is the form
using (Html.BeginForm("SendEmailToAdmin", "Home", FormMethod.Post, new { id = "form1" }))
{
#Html.Hidden("receiver", $"{user.Email}");
Customer Support
}
Here is the controller
[HttpPost]
[Route("/Home/SendEmailToAdmin")]
//[NonAction]
public JsonResult SendEmailToAdmin()
{
........
(some code
if is true )
return Json(new { status = "Thank you very much admin for showing up. Don't forget to send us the email of your feedback on your way out" }, JsonRequestBehavior.AllowGet);
}
(or else)
return Json(new { status = "Something went wrong, please try again" }, JsonRequestBehavior.AllowGet);
I have tried also using a button with the id of submitDemo
$('body').on('click', function (e) {
e.preventDefault();
alert("Handler for .click() called.");
$.post("~/Home/SendEmailToAdmin");
});
and also
$("#form1").submit(function (event) {
event.preventDefault();
$.post('#Url.Action("SendEmailToAdmin", "Home",new { id = email })');
document.signupform.submit();
});
have also tried using a variable for the button and then with onclick method and so on...
const button = document.getElementById('submitDemo');
EDIT : I HAVE TRIED THIS
I fount it at last.. here it goes!
Jquery:
$(document).ready(function () {
$("#submitBtn").click(function (event) {
console.log("sad");
event.preventDefault();
$.ajax({
type: "POST",
url: "#Url.Action("SendEmailToAdmin", "Home")",
data: "#email",
success: function () {
console.log("Done")
$("#form1").submit();
}
});
});
});
html in view : I added the btn outside of the form
and this way the submit form happens and also the post request!
using (Html.BeginForm("AdminSupport", "Home", FormMethod.Post, new { id = "form1" }))
{
#Html.Hidden("receiver", $"{user.Email}");
#*<button id="submitbutton" #user.Email=>Customer Support</button>*#
}
<button id="submitBtn" #*data-form-method="post"*#>Customer Support</button>

Looping json data using AngularJS in Asp.net MVC

I am trying to fetch records via ajax and displaying using AngularJS.
But my code even not invoking controller action.
I am trying this code..
<div ng-controller="MyCtrl">
<div ng-repeat="result in products">
{{result.ProductName}}
</div>
</div>
Ajax :
function MyCtrl($scope) {
$.ajax({
url: "/Products/Get/",
type: "POST",
success: function (data) {
// Success message
var myApp = angular.module('myApp', []);
$scope.products = data;
},
error: function () {
// Fail message
},
});
}
I am using this post to make it work.
Your approach is wrong.
You should use angularJS's controller directive to invoke services to consume json data.
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('MyCtrl', function ($scope, $http) {
$http.get('/Products/Get/').success(function (data) {
$scope.products = data;
});
});
</script>
I had written an article few days ago on the same.
You can go through here. This might be helpful.
you need declare module name in angularjs , and dont forget to add module name in you body or html tag..like this <body data-ng-app="app"> and then Try like this :
<script>
var app = angular.module('app',[]);
app.controller('MyCtrl',function($scope,$http){
bindData();
function bindData(
// it will be nice, if this code your separate to file service...
$http.get('/Products/Get').success(function (callBack) {
$scope.products = callBack.data;
});
);
});
</script>
and Best Implementation like This :
// in controller, injected you service name like this..
app.controller('MyCtrl',function($scope,$http ,myServices){
bindData();
function bindData(
var promiseGet = myServices.GetAll();
promiseGet.then(function(callBack){ // success
$scope.products = callBack.data;
}
,function(error){ // error
console.log(error);
});
);
});
app.service('myServices',function($http){
var vm = this;
vm.GetAll = function(){
return $http.get('/Products/Get');
}
});
and type not POST, if you want to Get data in ajax function..

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

C# MVC4: Replace <div> when selection is made from a Html.DropDownList using jQuery

I need to be able to populate data into a <div> or some other sort of section from an object after the corresponding string has been selected from a drop down list (lazy loading).
When a chnage is made in the dropdownlist, I want the method in my controller to be called which will fill in <div id=result></div> with the output from the method.
Perhaps I am approaching this problem wrong.
I suspect the problem is in my JavaScript.
Here is my approach:
View:
<div>#Html.DropDownList("MyDDL") </div>
<br>
<div id="result"></div>
JavaScript:
<script type ="text/javascript">
$(document).ready(function () {
$("#MyDDL").change(function () {
var strSelected = "";
$("#MyDDL option:selected").each(function () {
strSelected += $(this)[0].value;
});
var url = "HomeController/showInfo";
//I suspect this is not completely correct:
$.post(url, {str: strSelected},function (result) {
$("result").html(result);
});
});
});
</script>
Controller (Perhaps I shouldn't be using PartialViewResult):
public ActionResult Index()
{
List<string> myList = new List<string>();
List<SelectListItem> MyDDL = new List<SelectListItem>();
myList.Add("Tim");
myList.Add("Joe");
myList.Add("Jim");
//fill MyDDL with items from myList
MyDDL = myList
.Select(x => new SelectListItem { Text = x, Value = x })
.ToList();
ViewData["MyDDL"] = MyDDL;
return View();
}
[HttpPost]
public PartialViewResult showInfo(string str)
{
Person p = new Person(str); //name is passed to constructor
p.LoadInfo(); //database access in Person Model
ViewBag.Info = p.Info;
return PartialView("_result");
}
_result.cshtml:
<p>
#ViewBag.Info
</p>
Thanks You.
Change your script a little bit. Missing a # in the jQuery selecter for result div . Use the code given below
$.post(url, {str: strSelected},function (result) {
$("#result").html(result);
});
In my opinion if the javascript are in local don't need put $.post(url, {str: strSelected},function (result) {
You can use
//I suspect this is not completely correct:
$("#result").html(result);
try it
Did you try debugging p.LoadInfo() if it has any value? I also have some suggestions for your script:
Try adding keyup in your event so you can get the value in cases when the arrow keypad is used insted of clicking:
$("#MyDDL").on("change keyup", function () {
// you can get the dropdown value with this
var strSelected = $(this).val();
So I made the following changes and it worked:
View:
<div><%= Html.DropDownList("MyDDL") %> </div>
<br>
<span></span>
JavaScript:
<script type ="text/javascript">
$(document).ready(function () {
$("#MyDDL").change(function () {
var strSelected = $("#MyDDL option:selected").text();
var url = "/Home/showInfo";
$.post(url, {str: strSelected},function (result) {
$("span").html(result);
});
});
});
_result.cshtml:
#ViewBag.Info
The Controller was left unchanged.

passing a variable from cshtml razor to jquery

I have a partial view that I am calling on pages as follows :-
#Html.Partial("~/Views/Shared/ImageGallery.cshtml", Model)
The code for the actual Jquery of this page is a s follows :-
<script type="text/javascript">
$(document).ready(function () {
$('.modal_block').click(function (e) {
$('#tn_select').empty();
$('.modal_part').hide();
});
$('#modal_link').click(function (e) {
$('.modal_part').show();
var context = $('#tn_select').load('/Upload/UploadImage?Page=Article&Action=Edit&id=16', function () {
initSelect(context);
});
e.preventDefault();
return false;
});
});
</script>
Now this works perfectly, however I need to find a way to pass dynamic vars instead of hard coded vars to this :-
Upload/UploadImage?Page=Article&Action=Edit&id=16
In the Model I have all the vars, however I do not know how I can insert them into the Jquery. Any help would be very much appreciated!
---------UPDATE-----------------------
This is the code I am putting into each cshtml that needs the ImageGallery.
</div>
#Html.HiddenFor(model => model.PageViewModel.Page.PageTitle, new { id = "PageTitle"});
#Html.HiddenFor(model => model.PageViewModel.Page.PageAction, new { id = "PageAction"});
#Html.HiddenFor(model => model.ArticleViewModel.Article.ArticleID, new { id = "ArticleID"});
<div>
#Html.Partial("~/Views/Shared/ImageGallery.cshtml", Model)
</div>
New Javascript in the ImageGallery :-
<script type="text/javascript">
var pageTitle = $('#PageTitle').val();
var pageAction = $('#PageAction').val();
var id = $('#ArticleID').val();
$(document).ready(function () {
$('.modal_block').click(function (e) {
$('#tn_select').empty();
$('.modal_part').hide();
});
$('#modal_link').click(function (e) {
$('.modal_part').show();
var context = $('#tn_select').load('/Upload/UploadImage?Page=' + pageTitle + '&Action=' + pageAction + '&id=' + id, function () {
initSelect(context);
});
e.preventDefault();
return false;
});
});
</script>
This works fine now
You can add hidden field to your view and bind data form the model. Then you can easily read this value from jQuery.
View:
#Html.HiddenFor(model => model.Id, new { id = "FieldId"});
Script:
var id= $('#FieldId').val();
Also you can put this hiddens into your partial view. If your partial view is not strongly typed change HiddenFor to Hidden. Your ImageGallery partial view should contain the following div:
</div>
#Html.Hidden("PageTitle", Model.PageViewModel.Page.PageTitle);
#Html.Hidden("PageAction", Model.PageViewModel.Page.PageAction);
#Html.Hidden("ArticleID", Model.ArticleViewModel.Article.ArticleID);
<div>
In this case you don't need to put hiddens to every cshtml that needs the ImageGallery.
You can either set hidden fields or just declare javascript variables and set their values from either your model or the Viewbag, just like:
var action = #Model.action;
or
var id = #ViewBag.id;
and you can just use it in your code
<script type="text/javascript">
var action = #Model.action;
var id = #ViewBag.id;
$(document).ready(function () {
$('.modal_block').click(function (e) {
$('#tn_select').empty();
$('.modal_part').hide();
});
$('#modal_link').click(function (e) {
$('.modal_part').show();
var urlToLoad = "/Upload/UploadImage?Page=Article&Action=" + action + "&id=" + id;
var context = $('#tn_select').load(urlToLoad, function () {
initSelect(context);
});
e.preventDefault();
return false;
});
});
The following is another solution. I was in need of passing my api url declared in web.config to JavaScript (in this case Jquery)
In Razor declare a variable
#{var apiUrl= #System.Configuration.ConfigurationManager.AppSettings["BlogsApi"];}
Then in JavaScript
var apiUrl = '#apiUrl';

Categories

Resources