Ho to pass a Model Object or a Viewbag to Javascript? - c#

I am using asp.net mvc4 with C#. I get the details from Getdeatils() method of student class. This method return an array. Getdetails method also have same fields like studentBO. In the controller I have a method like follows
public ActionResult Index()
{
List<studentBO> list = new List<studentBO>();
Student.GetDetails[] dt = Student.Getdeatils();
for (int i = 0; i < dt.Length; i++)
{
studentBO.name= dt[i].name;
studentBO.studentno= dt[i].studentno;
studentBO.address= dt[i].address;
list1.Add(studentBO);
}
ViewBag.Registrationlist = list1;
return View(list1);
}
studentBO object have 3 fields
public class studentBO
{
public long studentno{ get; set; }
public string name{ get; set; }
public string address{ get; set; }
}
How can I get viewbag or model in my Jquery `$(document).ready(function () {}` function. I want to get every students name. So I have to use foreach loop as well.

You can serialise your item in the ViewBag and write it to the view, so that the Javascript code will be able to read it:
$(document).ready(function() {
var registrationList = #(Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ViewBag.Registrationlist)));
for (var i = 0; i < registrationList.length; i++) {
var studentno = registrationList[i].studentno;
var name= registrationList[i].name;
var address= registrationList[i].address;
// write some more code to make use of the values
}
});

Use WebAPI to create a service that returns your objects. Then you can use an ajax-call in your Javascript code to fetch the objects.
WebAPI:
public class StudentsController : ApiController
{
IEnumerable<Student.GetDetails> GetDetails()
{
List<studentBO> list = new List<studentBO>();
Student.GetDetails[] dt = Student.Getdeatils();
for (int i = 0; i < dt.Length; i++)
{
studentBO.name= dt[i].name;
studentBO.studentno= dt[i].studentno;
studentBO.address= dt[i].address;
list1.Add(studentBO);
}
return list1;
}
}
Javascript:
$(document).ready(function () {
// Send an AJAX request
$.getJSON("api/students")
.done(function (data) {
// On success, 'data' contains a list of students.
$.each(data, function (key, item) {
//Do something with the student object
});
});
});

Related

Show buttons on a partial view based on some query

I am showing search results same as searching groups on facebook
enter image description here
I have a relationship Table named CommunityUser in Database having attributes CommunityID and UserID.
Using Partial View I want to show if User not already joined that Community/Group that it will show Join Button else if user already joined that community it will show Leave button.
I have written IsMember() function in my controller that takes two parameters, CommunityID and UserID. This will return true if that Community ID exist against that user ID.
public bool IsMember(string UserID, int CommunityID) {
var Membership = db.Users.Include(x => x.CommunityUsers).Where(s => s.Id.Equals(UserID)).Count();
if(Membership>0)
return true;
else
return false;
}
Now what I actually need is, I want to call this function in an IF condition on my view class. It is not allowing me to call this function on my view Class.
#if (){
<button>#Html.ActionLink("Leave", "LeaveCommunity", new { id = ViewBag.ComID })</button>
}
else
{
<button>#Html.ActionLink("Join", "joinCommunity", new { id = ViewBag.ComID })</button>
}
In your controller you should have a method which will return this view. So in this method you call this function
public ActionResult Index(string UserID, int CommunityID)
{
var hasMembership = IsMember(serID, CommunityID);
return View(hasMembership);
}
In the View it self then you just grab this variable hasMembership you just passed from #model.
#if (Model){
<button>#Html.ActionLink("Leave", "LeaveCommunity", new { id = ViewBag.ComID })</button>
}
else
{
<button>#Html.ActionLink("Join", "joinCommunity", new { id = ViewBag.ComID })</button>
}
Note: it might be wise to create some DTO class for passing data to a view, because you might need to pass multiple value to a view at some point. Plus the whole condition would be more readable
public SomeDTO {
public bool IsMember {get;set}
public List<Community> Communities {get;set;}
}
public ActionResult Index(string UserID, int CommunityID)
{
var hasMembership = IsMember(serID, CommunityID);
var listOfCommunities = _repo.GetComunities();
var dto = new SomeDTO
{
IsMember = hasMembership,
Communities = listOfCommunities
}
return View(dto);
}
#if (Model.IsMember){
// do or do not something
}

WebApi2 how to pass Json with an array

I have the following Json with array that I am sending it from AngularJS
{id_fleet: 4177, id_fleetfeature: Array[2]}
var dataFeatures = {
id_fleet: $scope.id,
id_fleetfeature: $scope.selectedFeatures
}
$http.put(myUrl + "Fleets/Insert", JSON.stringify(dataFeatures)).then(function () {
Materialize.toast('Features insertadas correctamente', 3000);
$scope.refreshData();
});
Web API Model
public class modelFleetFeatures {
public int id_fleet { get; set; }
public int[] id_fleetfeature { get; set; }
}
Web API Function
[HttpPut]
[Route("api/Fleets/FleetFeature/Update")]
public HttpResponseMessage updateFleetFeature(List<modelFleetFeatures> data)
{
var cnt = 0;
foreach (var item in data)
{
db.sp_Fleet_FleetFeaturesDelete(item.id_fleet);
db.SaveChanges();
}
foreach (var item in data)
{
db.sp_Fleet_FleetFeaturesInsert(item.id_fleet, item.id_fleetfeature[cnt]);
db.SaveChanges();
cnt +=1;
}
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}
In the Web API the value of data always gets null
You are sending single object in JSON, so why expecting list of object in API action?
Just expect single object in api Action , you will get that object model in call like :
public HttpResponseMessage updateFleetFeature(modelFleetFeatures data)
{
//do stuff
}
And no need to stringify json object in put request.
$http.put(myUrl + "Fleets/Insert", dataFeatures).then(function () {
Materialize.toast('Features insertadas correctamente', 3000);
$scope.refreshData();
});

AngularJS object is not properly converted into a ViewModel .NET

I have an AngularJS directive which returns me an array with some values, like this below:
The AngularJS code I'm using to generate this object like above is:
//--------------------------
// service...
service.getSelectedOptions = function() {
var options = [];
for (var I = 0; I < service.optionList.length; ++I) {
var availableOption = service.optionList[I];
if (availableOption.selecionado !== '') {
options.push(availableOption);
}
}
return opcoes;
};
//--------------------------
// controller...
var options = [];
var list = OptionsService.getSelectedOptions();
for (var I = 0; I < list.length; ++I) {
var option = list[I];
options.push({ Handle: option.Handle, Selecionado: option.Selecionado });
}
console.log(options);
// Sending the values to backend...
doPost('..../SaveOptions', { options: options }, function (result) { });
Ok, I created a ViewModel class to receive those objects into my controller.
public class OptionsViewModel {
public int Handle { get; set; }
public string Selecionado { get; set; }
}
My controller is declared like this below:
public JsonResult SaveOptions(OptionsViewModel[] options) {
//...
}
The problem is: if I chose 4 options, the array in the backend has 4 options, but the values are not binded to the objects.
Why that? Anyone knows why? Thanks!!
The solution was modify two parameters in the AJAX call:
Set contentType: "application/json";
Use JSON.stringify(parameters) to the parameters.
Thanks!

Populating sub menu using Jquery

I feel like a pain asking for help ALL the time but I guess that's what here is for.
New to C# MVC and new to JQuery. I'm not entriely sure about the program flow of things when it comes to Jquery and MVC.
There really isn't that much on tutorials. This is what I want to happen. Select a type of animal (dog) and return list of breeds in sub menu.
#using(Html.BeginForm("", "Pictures", FormMethod.Get))
{
Project1.Models.Animal animal = new Project1.Models.Animal();
#:Filter Photos
<span>
Filter by animal
#Html.DropDownList("animal", new List<SelectListItem> {
new SelectListItem {Text="Select Animal", Value=""},
new SelectListItem {Text="Dog", Value="dog"},
new SelectListItem {Text="Cat", Value="cat"},
})
</span>
//This is where I want jQuery to update the dropdownlist
<span>
Filter by breed
#Html.DropDownList("breed", new SelectList(animal.DogBreeds), "Choose a breed")
</span>
//End of wanted dynamic jquery dropdownlist
<span>
<input type="submit" value="Filter" />
</span>
}
Here is the jquery code
<script type="text/javascript">
$(document).ready(function () {
$("#animal").change(function () {
var animalType = $("#animal option:selected").text();
alert($("#animal option:selected").text());
$.ajax({
type: "POST",
url: "Pictures/GetBreed",
data: animal = animalType,
success: function (data) {
$("#breed").html(data);
}
});
});
})
</script>
And what I want populating is a predefined list. This is just a sample of the list of course
public class Animal
{
public List<string> DogBreeds = new List<string>()
{
"Affenpinscher","Afghan Hound","Airedale Terrier","Akita","Alapaha Blue Blood Bulldog",
"Alaskan Malamute","American Bulldog","American Cocker Spaniel","Anatolian Shepherd",
"Australian Cattle Dog","Australian Shepherd"
};
public List<string> CatBreeds = new List<string>()
{
"Abyssinian","Aegean Cat","Australian Mist","American Curl"
};
}
And here is Pictures/GetBreed, I think this is the bit i'm struggling with. I'm not sure of the correct way to return the data. What do I do!? IS this even the correct way?
public ActionResult GetBreed()
{
string animal = Request["animal"];
if (animal == "Dog")
return dog list;
elseif (animal == "Cat")
return cat list;
else
return null;
}
Thanks for any help!
MVC makes it very simply to pass json data between the client and your controller actions, you could take the following approach.
Javascript
You can get the selected animal type with the following:
var animalType = $('#animal').val()
You could use the getJson method as follows, please note you can also use Url.Action to populate the url i.e. #Url.Action("GetBreed"):
$.getJSON("Pictures/GetBreed", { animalType: animalType }, function (animals) {
// clear the select list
var breedSelect = $('#breed');
breedSelect.empty();
$.each(animals, function (index, breed) {
breedSelect.append($('<option/>', {
value: breed.Id,
text: breed.Name
}));
});
To explain what is happening in the above, a json object is passed as the argument i.e. { animalType: animalType }.
The cascading menu is emptied, the json data that is returned from the controller is looped adding an option to the select list.
Model
The above assumes a new model is created with an Id and a Name i.e.
public class Breed
{
public int Id { get; set;}
public string Name { get; set; }
}
Controller
Then change your controller action to return json as follows:
public ActionResult GetBreed(string animalType)
{
var breeds = new List<Breed>();
if (animalType == "Dog")
breeds = GetDogList();
else if (animalType == "Cat")
breeds = GetCatList();
return Json(breeds, JsonRequestBehavior.AllowGet);
}
The GetDogList and GetCatList just need to return a list of the Breed objects i.e.
private List<Breed> GetDogList()
{
var dogs = new List<Breed>();
dogs.Add(new Breed { Id = 1, Name = "Collie" });
....
return dogs;
}

Deserialize javascript objects to generic list in c# handler

Im creating some javascript items in a loop
var licenseList = {};
$($licenses).each(function (index) {
var license = {};
var editedValues = {};
license.PRODUCT_KEY = $(this).parent('div.licensewrapper').data('productkey');
$(this).find('input:text').each(function (i, val) {
if ($(val).attr('data-default-value') != $(val).val() && $(val).val() > 0 && $(val).data('isValid') != false) {
var pogKey = $(val).data('product_option_group_key');
var editedValue = $(val).val();
editedValues[pogKey] = editedValue;
license.editedValues = editedValues;
}
});
//licenseList[index] = license;
//liceneList.push(license); //if array...
});
I've commented out my current solutions. But i dont think any of the two are equal to a generic list when derelializing them in c#. Whats the corrent way to do it in this case? Thanks
create your array
var licenseList = [];
for each of your licenses...
var license = {
prop1: 'p1',
prop2: 'p2'
};
licenseList.push(license);
format and serialize JSON data to be sent over to webmethod
data = {
LicenseList: licenseList
};
$.ajax({
...
data: JSON.stringify(data)
...
});
in your webmethod your method parameter must match
[WebMethod]
public static string GetLicenses(List<License> LicenseList)
{
foreach(var license in LicenseList)
{
// do whatever
}
}
sample license class. Your properties need to match with your objects in your javascript
public class License
{
public string Prop1 {get; set;}
public string Prop2 {get; set;}
}
Hope this helps.
function sendToServer(licenseList)
{
var url = "controller.ashx";
var data = {};
data.SerializedObj = JSON.stringify(licenseList);
$.post(url, data, function(response){
if(response.length > 0)
{
alert(response);
}
});
}
//controller.ashx :
public void ProcessRequest (HttpContext context) {
//...
string serializedObj = context.Request.Form["SerializedObj"] ?? "";
JavaScriptSerializer js = new JavaScriptSerializer();
List<license> collection = js.Deserialize<List<license>>(serializedObj);
//...
public class license
{
public string Propertie1 {get;set;}
public string Propertie2 {get;set;}
}
Javascript object must have the same properties:
var license = {Propertie1 : 'value1', Propertie2 : 'value2'};

Categories

Resources