JQuery: Retrieving a list of ids/Names by hover - javascript

How do I make a div(<div id="HoverMe">) hoverable, and display a list of names from AllCarId-list (by return Car.Name in place of Car.Id)?
I got two tables Owner(Id) and Car(Id, OwnerId, Name).
I have a property TotCar in ViewModel where I use Count() in controller to add total Car.OwnerId = Owner.Id in model.TotCar.
I also got public List<Guid> AllCarId { get; set; }inside the ViewModel to pass OwnerId to list for every related Owner.Id = Car.OwnerId.
So far I got this where I currently show the count-value of TotCar:
<div id="HoverMe">
#Html.DisplayFor(model => model.TotCar)
</div>
#*I want this to be hoverable and list all from AllCarId(convert to name) in a "listbox"*#
So how do I make <div id="HoverMe"> hoverable, once it hovers, list every items in AllCarId?
This is how I pass id's to AllCarId in Controller.
List<Guid> GetCarIds = db.Cars.Where(c => c.OwnerId == id).Select(c=> c.OwnerId).ToList();
Then I pass GetCarIds to model public List<Guid> AllCarId { get; set; } property.
EDIT: related property from models:
ViewModel:
public List<Guid> AllCarId { get; set; }
public int TotCar { get; set; }
public virtual Car Car { get; set; }
Car:
public System.Guid Id { get; set; }
public System.Guid OwnerId { get; set; }
public string Name { get; set; }
Owner:
public System.Guid Id { get; set; }

Related

Have to show Model data into View using JavaScript MVC C#

I have page where I save user, contact and address details. The users could have multiple contact and address, So I have added the control to populate dynamically.
Form is working fine, except if any exception occurrs, the controller action return view with model.
This follows the structure of Model:
Model
public class UserModel
{
public UserDetail User { get; set; }
public IList<UserContact> Contact { get; set; }
public IList<UserAddress> Address { get; set; }
}
Contact Model :
public partial class UserContact
{
public int Id { get; set; }
public int UserId { get; set; }
public string ContactType { get; set; }
public string Mobile { get; set; }
public string Email { get; set; }
public bool IsActive { get; set; }
public virtual UserDetail UserDetail { get; set; }
}
Address Model
public partial class UserAddress
{
public int Id { get; set; }
public int UserId { get; set; }
public string AddressType { get; set; }
public string AddressName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostCode { get; set; }
public bool IsActive { get; set; }
public virtual UserDetail UserDetail { get; set; }
}
When value return, the following function suppose to check the Contact and Address and then then populate each record in dynamic created input section in view.
<script type="text/javascript">
$(document).ready(function () {
AddDynamicData();
function AddDynamicData() {
var valuesContacts = eval('#Html.Raw(Json.Encode(Model.Contact))');
var valuesAddresses = eval('#Html.Raw(Json.Encode(Model.Address))');
if (valuesContacts != null) {
var iContact = 0;
$(valuesContacts).each(function () {
$("#divContact").append(GetDynamicContact(iContact++, valuesContacts.contactType, valuesContacts.mobile, valuesContacts.email));
});
}
if (valuesAddresses != null) {
var iAddress = 0;
$(valuesAddresses).each(function () {
$("#divAddress").append(GetDynamicAddress(iAddress++, valuesAddresses.addressType, valuesAddresses.addressName, valuesAddresses.addressLine1, valuesAddresses.addressLine2, valuesAddresses.city, valuesAddresses.state, valuesAddresses.postCode));
});
}
}
</script>
The Function does not work properly, It does create the field but does not populate the user input data into textbox... Please advise how to fix the same and how to populate the records in view....
Added the View after submitting the form
<Update>
#Updated New Code with function & added screenshot
</Update>

How to send selected values to viewModel from multiselect (Kendo MultiSelect)

I'm using Kendo MultiSelect in my mvc5 project. So I have a View with multiselect:
#model Library.ViewModels.Models.BookViewModel
#{
ViewBag.Title = "Edit";
}
<script>
$(document).ready(function () {
$("#multiselect").kendoMultiSelect({
placeholder: "--Select Public Houses--",
dataTextField: "PublicHouseName",
dataValueField: "PublicHouseId",
autoBind: true,
dataSource: {
transport: {
read: {
dataType: "json",
url: "/book/getallpublichouses"
}
}
}
});
});
</script>
And I have 2 viewModels:
public class BookViewModel
{
public int BookId { get; set; }
public string Name { get; set; }
public string AuthorName { get; set; }
public int YearOfPublishing { get; set; }
public ICollection<PublicHouseViewModel> PublicHouses { get; set; }
}
public class PublicHouseViewModel
{
public int PublicHouseId { get; set; }
public string PublicHouseName { get; set; }
public string Country { get; set; }
public ICollection<BookViewModel> Books { get; set; }
}
In my Kendo MultiSelect a get all Public Houses from Book controller in JSON format. Next I selected some values:
So, how can I pass this selected values in public ICollection<PublicHouseViewModel> PublicHouses { get; set; } property in BookViewModel ?
You can use:
public int[] PublicHouses { get; set; }
instead of:
public ICollection<PublicHouseViewModel> PublicHouses { get; set; }
Or you can create a new field in BookViewModel only for posting.
When you are posting values from kendoMultiSelect, he posts only "dataValueField". After you post only id's you can do the rest of the logic in POST action.
It depends how you implemented your POST action and also on the relationship between two tables: Is it 1...N, or N....N.

Service Return Empty Lists To Api Controller

I am working in service fabrics micro services , where i need to fetch record for an object. when I send request to API , it shows me empty lists while rest of the data is in place. while debugging I came to know that before returning to API controller my service object has all the data expected i.e lists has data , but when it comes back to web API the lists are empty.
After searching for solution over web I came to know that every time a request is to the API the lists are recreated , so it shows empty result. Any Solutions to come out of this problem?
Here is my piece of code.
The following Is the Web Api Method.
[HttpGet()]
[Route("edit/{readingListId}")]
[ProducesResponseType(typeof(List<GetReadingListDTO>), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(List<GetReadingListDTO>), (int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> GetReadingListById(int readingListId)
{
try
{
var readingList = await this._readingListService.GetReadingListByIdAsync(readingListId);
return Ok(readingList);
}
catch (Exception ex)
{
this._logger.LogError(ex.Message);
return BadRequest();
}
}
The following Is the Service Method.
public async Task<Domain.ReadingList> GetReadingListByIdAsync(int readingListId)
{
try
{
Domain.ReadingList readingList = await _repository.FindById(readingListId);
return readingList;
}
catch (Exception ex)
{
throw;
}
}
Moreover , This Is My Entity.
public class ReadingList : EntityBase, IAggregateRoot, IAggregateCreateRoot, IAggergateUpdateRoot, IAggregateDeleteRoot
{
public ReadingList()
{
this.Items = new List<ReadingListItem>();
this.Assignees = new List<ReadingListAssignee>();
}
public int Id { get; set; }
public EntityType EntityTypeId { get; set; }
public int EntityId { get; set; }
public string Title { get; set; }
public DateTime CompletionDate { get; set; }
public int ReminderDay { get; set; }
public string ReminderDayType { get; set; }
public bool SendReminder { get; set; }
public int CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public int? UpdatedBy { get; set; }
public DateTime? UpdatedDate { get; set; }
public int? DeletedBy { get; set; }
public DateTime? DeletedDate { get; set; }
public bool? Deleted { get; set; }
public List<ReadingListItem> Items { get; private set; }
public List<ReadingListAssignee> Assignees { get; private set; }
}
Thanks!
Edited
The Issue Was Resolved , By Simply Changing The dll Versions.One Of The Service Had And Old Version While The Version Was Updated In The Other One.
Thanks For The Help.

How can I get field from second table via first table with foreign key from javascript?

I have two simple models:
Book:
public class Book
{
public int BookID { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public string Year { get; set; }
public string Publisher { get; set; }
public int GenreId { get; set; }
[ForeignKey("GenreId")]
public Genre Genre { get; set; }
}
and Genre
public class Genre
{
public Genre()
{
Books = new List<Book>();
}
public int GenreID { get; set; }
public string Name { get; set; }
public ICollection<Book> Books { get; set; }
}
With method from ApiController I get all data from table Books.
How can I get in javascript code Name of genre from table Genres using foreign key GenreId ?
I would like to write something like book.Genre.Name, but it does not work in js
You can try below code to serialize the object to return to frontend with json format:
var genre = new Genre();
JavaScriptSerializer js = new JavaScriptSerializer();
string data = js.Serialize(Genre);
Or in other way, you can use Json.NET for do that, this is a powerful json object convert lib.

How to display foreign key value from a model to a cascaded dropdown list in mvc5?

I'm still new to mvc5 and had very little knowledge with javascript. I know that my cascading works but I'm having trouble with the display part. What I want to do is have 2 dropdown list. 1 containing all customer names and the 2nd will have a list of their pending transactions. Basically 1st dropdown will have customer names while the 2nd will have video titles. Please check my code where I did wrong. Why I can't display the video titles. BTW I tried other properties in my transactions and I can display them. That's how I know that my cascading is not the problem.
Models
//Transaction Model
TransactionID { get; set; }
public int CustomerID { get; set; }
public virtual Customers CustomerName { get; set; }
public int VideoID { get; set; }
public virtual Videos Videos { get; set; }
public int Quantity { get; set; }
[ReadOnly(true)]
public DateTime? TransactionDate { get; set; }
[ReadOnly(true)]
public DateTime? DueDate { get; set; }
[ReadOnly(true)]
public Decimal Cost { get; set; }
[ReadOnly(true)]
public String ReturnStatus { get; set;}
//Customers Model
public int CustomerID { get; set; }
public string CustomerName { get; set; }
public string CustomerAddress { get; set; }
public string CustomerContact { get; set; }
//Video Model
public int VideoID { get; set; }
public string VideoTitle { get; set; }
public int CategoryID { get; set; }
public virtual Category VideoCategory { get; set; }
[Range(0,99)]
public int VideoIn { get; set; }
[Range(0,99)]
public int VideoOut { get; set; }
Conroller
public ActionResult CustomerList()
{
var customers = db.Customers.OrderBy(x => x.CustomerID).ToList();
if (HttpContext.Request.IsAjaxRequest())
{
return Json(new SelectList(
customers,
"CustomerID",
"CustomerName"), JsonRequestBehavior.AllowGet
);
}
return View(customers);
}
public ActionResult Transact(int cusId)
{
var transact = db.Transactions
.Where(x => x.CustomerID == cusId)
.Where(s => s.ReturnStatus == "FALSE").ToList();
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
transact,
"TransactionID",
"VideoTitle"), JsonRequestBehavior.AllowGet
);
return View(transact);
}
I figure out a solution after hours of trial an error. What I did is I added a join in my query.
var transact = db.Transactions
.Where(x => x.CustomerID == cusId)
.Where(s => s.ReturnStatus == "FALSE")
.Join(db.Videos,
v => v.VideoID,
t => t.VideoID,
(transaction, videos) => new {
TransactionID = transaction.TransactionID,
VideoTitle = videos.VideoTitle }).ToList();

Categories

Resources