asp.net core and ajax - ajax

I'm working on ASP.NET Core application and not sure what is right way to use ajax in it.
For example, I have model:
public class Person
{
public int ID { get; set; }
public string Wiki { get; set; }
public string Name { get; set; }
}
Controller, for show list of items:
public async Task<IActionResult> Index()
{
return View(await _context.Person.ToListAsync());
}
And view:
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
<a asp-action="Details" asp-route-id="#item.ID">#Html.DisplayFor(modelItem => item.Name)</a>
</td>
</tr>
}
</tbody>
</table>
When I press on item I want to get item's details.
I have action Details(int? id) and view Details.cshtml.
And I created ViewModel:
public class PersonViewModel
{
public string Name { get; set; }
public string Description { get; set; }
public string Birthday { get; set; }
public string Death { get; set; }
public string Image { get; set; }
public string Link { get; set; }
}
But this information I get from Wikidata using ajax.
I can run ajax by pressing link on the item and I get json from Wikidata.
But how I can populate ViewModel? For this I need to call action Details from ajax. But ajax usually used for get information on the current page (to avoid postback). So in this case it doesn't belong here.
Or I can call ajax when loading Detals view and populate page information. But in this case I don't need ViewModel at all.
What is right way to use ajax in my application?

Related

How to get User model field inside Razor page?

I am using asp.net core with Identity. For user I have this class:
public class User : IdentityUser
{
public List<Rate> Rates { get; set; }
}
I would like to get Rates inside Razor, how can this be done with the Name field (User.Identity.Name).
First, please confirm whether you have successfully added a one to many relation of Rate table for Identityuser and generated the Rate
table in the database.
Please change all Identityuser references (except where the User class inherits) in your project to your customized User class, including the relevant view page and the startup class.
And then change the ApplicationDbContext as follow:
public class ApplicationDbContext : IdentityDbContext<User>
{
public DbSet<Rate> Rate { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
Then excute migration command. More details, refer to this video.
Here is my Rate Class:
public class Rate
{
[Key]
public int Id { get; set; }
public int rate { get; set; }
public virtual User User { get; set; }
}
After completing the above operations, add relevant Rates data to the database.
Then start the project, log in the user information, and then use the following code in the corresponding action and view to show Rates of associated Name field:
[Authorize]
public class AccountController : Controller
{
private readonly ApplicationDbContext _context;
public AccountController(ApplicationDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
var rates = await _context.Rate.Include(host => host.User).Where(x => x.User.UserName == User.Identity.Name).ToListAsync();
return View(rates);
}
}
Razor View:
#model IEnumerable<Rate>
#{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Index</h1>
UserName: #User.Identity.Name related Rates data:
<table class="table table-bordered">
<tr>
<th>Id</th>
<th>Rate</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#item.Id</td>
<td>#item.rate</td>
</tr>
}
</table>
Here is the test result:

mvc 5 ajax: httpError 400.0 Bad request

having trouble with ajax i am using vs 2015 mvc 5.
following are the two model classes which have 1 to many relation.
i am facing some problem.
the view doesn't produce expected links i.e. instead
~/Global/Cities/Details/1 it result ~/Global/Cities/Details/ only.
when i fix that manually in browser it through httperror 400.0 Bade Request
when i remove Url property from ajax options the partial view opens in new tab window
namespace WebApplication1.Areas.Global.Models
{
public class Organization
{
public virtual int OrganizationId { get; set; }
public virtual int CityId { get; set; }
public virtual string Name { get; set; }
public virtual City city { get; set; }
}
public class City
{
public virtual int CityId { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<Organization> Organization { get;set; }
}
}
and this is the partial view controller..
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
City city = db.Cities.Find(id);
if (city == null)
{
return HttpNotFound();
}
return PartialView(city);
}
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DropDownList("Organizations",new SelectList(item.Organization, "OrganizationId","Name"))
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.CityId }) |
#Ajax.ActionLink("Details", "Details",item.CityId,
new AjaxOptions
{
UpdateTargetId = "detail",
Url = Url.Action("Details",item.CityId)
}, new { id=item.CityId }) |
#Html.ActionLink("Delete", "Delete", new { id=item.CityId })
</td>
</tr>
i have also render jqueryval bundle in layout page...
is there any problem with my code please help....

How to pass complex params into controller?

This is just my 2nd week on ASP.NET MVC
Basically I have a model called T_Users, in the view page I created a textbox for creating a new record into the database, below is the code:
<th scope="row" class="spec">Row</th>
<th scope="col" class ="nobg">#Html.TextBoxFor(A => A.Username)</th>
<th scope="col" class ="nobg">#Html.PasswordFor(p => p.Password)</th>
...
How can the controller behind it can get the values? Obviously pass by /xx/xx/ID is not a efficient way.
If you post the form to a Action, depending on the method of that form you will get the values in a collection.
For example:
HTML
<form action="SubmitAction" method="POST">
<...>
<th scope="row" class="spec">Row</th>
<th scope="col" class ="nobg">#Html.TextBoxFor(A => A.Username)</th>
<th scope="col" class ="nobg">#Html.PasswordFor(p => p.Password)</th>
<.../>
Code Behind
[HttpPost]
public ActionResult SubmitAction(UserInfo user)
{
var value1 = user.Username;
var value2 = user.Password;
...
... return something ...
}
and the model
class UserInfo
{
public string Username { get; set; }
public string Password{ get; set; }
}
create a model class to represent your record:
class UserInfo
{
public string Username { get; set; }
public string Password{ get; set; }
}
Now create a HttpPost action Save that accepts your UserInfo class as parameter:
[HttpPost]
public ActionResult Save(Userinfo info)
{
//info should contain your username and password
}
Make sure that the Property names in your class match exactly the name in you html form.

How to get data from two table or two class in single view in mvc3

How to get data from two table or two class in single view in mvc3.
I want to show data from both the table.
I have one parent class and two child class.
i.e
public class GetDocumentParent
{enter code here
public List getDocument { get; set; }
public List getDocumentRevision { get; set; }
}
View:
" %>
<% foreach (var item in Model.getDocument)
{ %>
<tr>
<td>
<%:Html.DisplayFor(ModelState => item.DOCUMENT_NAME)%>
</td>
<td>
<%:Html.DisplayFor(ModelState => item.ActiveDate)%>
</td>
<td>
<%:Html.DisplayFor(ModelState => item.Revision)%>
</td>
<td>
</tr>
<% } %>
==>item.DOCUMENT_NAME and item.ActiveDate from Document Class.
item.Revision from Document_Revision class.
how to show both class's value at the same time in view.
Controller:
var model = new GetDocumentParent
{
getDocument = db.Document.ToList(),
getDocumentRevision = db.DocumentRevisions.ToList()
};
return View(model);
Model:
1.
public class DOCUMENTS
{
public string DOCUMENT_NAME
{
get;
set;
}
public Nullable<System.DateTime> ActiveDate
{
get;
set;
}
}
2.
public class DOCUMENT_REVISIONS
{
public string REVISION
{
get;
set;
}
}
Thanks in advance
Always remember that it is best to have a view model that represents your data that is sent to the view. The view will do what is needed with you view model. The code below can guide you, you must just change it to fit into your scenario.
Lets say that I have a customer and each customer has only 1 address. I would create a view model called CustomerDetailsViewModel to represent this data:
public class CustomerDetailsViewModel
{
public string FirstName { get; set; }
public string Lastname { get; set; }
public int Age { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
}
Your action method to display the customer and customer address details:
public class CustomerController : Controller
{
private readonly ICustomerRepository customerRepository;
public CustomerController(ICustomerRepository customerRepository)
{
// Check customerRepository for nulls
this.customerRepository = customerRepository;
}
public ActionResult Details(int id)
{
// Check that id is not zero or negative
Customer customer = customerRepository.GetById(id);
// Get the customer's address
Address address = customerRepository.GetCustomerAddress(id);
CustomerDetailsViewModel viewModel = new CustomerDetailsViewModel()
{
FirstName = customer.Firstname,
LastName = customer.LastName,
Age = customer.Age,
AddressLine1 = address.AddressLine1,
AddressLine2 = address.AddressLine2,
City = address.City
}
return View(viewModel);
}
}
id above represents your customer's unique identifier. It is used to return a cusotmer:
Customer customer = customerRepository.GetById(id);
and also used to returned a specific customer's address:
Address address = customerRepository.GetCustomerAddress(id);
An ICustomerRepository instance is injected by an IoC container for example Autofac.
In your view you pass this view model as such and can display the data as you please:
#model MyProject.DomainModel.ViewModels.Customers.CustomerDetailsViewModel
<div class="content">
<div class="display-label">First Name: </div>
<div class="display-content">#Model.FirstName</div>
<div class="display-label">Last Name: </div>
<div class="display-content">#Model.LastName</div>
<div class="display-label">Age: </div>
<div class="display-content">#Model.Age</div>
<div class="display-label">Address Line 1: </div>
<div class="display-content">#Model.AddressLine1</div>
<div class="display-label">Address Line 2: </div>
<div class="display-content">#Model.AddressLine2</div>
<div class="display-label">City: </div>
<div class="display-content">#Model.City</div>
</div>
I hope this helps.
What is the problem?
use in controller:
var model = new GetDocumentParent();
model.getDocument = ...//Code that initialize getDocument
model.getDocumentRevision =...//Code that initialize getDocumentRevision
in View:
#Html.EditorFor(m=>m.getDocument);
#Html.EditorFor(m=>m.getDocumentRevision);

MVC 3 Error for Navigating between Models in View

I've been stuck in this issue for the whole afternoon, appreciate if anyone can tell me how, Thanks!
I am using MVC 3 and setup two models:
public class Employee
{
[Key]
public virtual int Id { get; set; }
public virtual string Emp_Id { get; set; }
public virtual string Emp_Name { get; set; }
public virtual int Emp_Type { get; set; }
public virtual ICollection<Job> Jobs { get; set; }
}
public class Job
{
[Key]
public virtual int Id { get; set; }
public virtual string SO { get; set; }
public virtual int? Manhour_Type { get; set; }
public virtual DateTime? StartJob { get; set; }
public virtual DateTime? EndJob { get; set; }
public virtual double? Duration { get; set; }
public virtual Employee employee { get; set; }
}
Two databases are generated by this code:
public class JMCDB : DbContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<Job> Jobs { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Job>().HasRequired(j => j.employee).WithMany(e => e.Jobs);
}
}
I Create the JobController as follows:
public class JobController : Controller
{
//
// GET: /Job/
JMCDB _db = new JMCDB();
public ActionResult Index()
{
var job = _db.Jobs;
return View(job);
}
}
In "View", I wanna see the employee name of this specific job:
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.SO)
</td>
<td>
#Html.DisplayFor(modelItem => item.Manhour_Type)
</td>
<td>
#Html.DisplayFor(modelItem => item.StartJob)
</td>
<td>
#Html.DisplayFor(modelItem => item.EndJob)
</td>
<td>
#Html.DisplayFor(modelItem => item.employee.Emp_Name)
</td>
<td>
</td>
</tr>
}
But when I run the program, there is an error for the last line of code
"#Html.DisplayFor(modelItem => item.employee.Emp_Name)"
I don't know how to solve, Thanks if anyone can tell me how.
You can use the Include method to eager load the navigational property employee
public ActionResult Index()
{
var job = _db.Jobs.Include(job => job.employee);
return View(job);
}

Resources