How to pass complex params into controller? - asp.net-mvc-3

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.

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:

asp.net core and 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?

Learning ASP.NET MVC 3 EntityFramework library 4.1.0.0 (not the latest) and getting no data

My context is:
public class RegistrationManagerContext : DbContext
{
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.ToTable("aspnet_Users");
}
}
and my User class is:
[Table("aspnet_Users")]
public class User
{
[Key]
[Display(AutoGenerateField = true)]
[Required]
public Guid UserId { get; set; }
[DataType("nvarchar")]
[MaxLength(256)]
[Required]
public string UserName { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, ConvertEmptyStringToNull = true, DataFormatString = "{0:d}")]
[Required]
public DateTime LastActivityDate { get; set; }
[NotMapped]
public AccountProfile Profile
{
get
{
if (_profile == null)
{
_profile = AccountProfile.GetUserProfile(this.UserName);
}
return _profile;
}
}
private AccountProfile _profile = null;
}
and my call method (Controller) is:
namespace RegistrationManager.Controllers
{
[Authorize(Roles="Admins")]
public class AdminController : Controller
{
private RegistrationManagerContext db = new RegistrationManagerContext();
//
// GET: /Admin/
public ActionResult Index(int? id)
{
var viewModel = db.Users;
if (id.HasValue)
{
ViewBag.UserID = id.Value;
}
return View(viewModel);
}
}
}
My view is:
#model IEnumerable<RegistrationManager.Models.User>
#{
ViewBag.Title = "Users";
}
<h2>Users</h2>
<table>
<tr>
<th>Email Address</th>
<th>Given Names</th>
<th>Surname</th>
<th>Last Ac</th>
<th>Refresh</th>
</tr>
#foreach (var item in Model)
{
string selectedRow = "";
if (ViewBag.UserId != null && item.UserId == ViewBag.UserId)
{
selectedRow = "selectedrow";
}
<tr class="#selectedRow" valign="top">
<td>
#item.UserName
</td>
<td>
#item.Profile.GivenNames
</td>
<td>
#item.Profile.Surname
</td>
<td>
#String.Format("{0:d}", item.LastActivityDate)
</td>
<td>
#Html.ActionLink("Refresh", "Refresh", "Admin", new { id = item.UserId })
</td>
</tr>
}
</table>
So what am I doing wrong or what am I missing?? As I get no data!!?? There is definitely data as I should at least see my own login, right!?
Shouldn't you be doing something like this:
public ActionResult Index(Guid? id)
{
if (id.HasValue)
{
var viewModel = db.Users.Where(x=>x.UserId == id.Value).FirstOrDefault();
//ViewBag.UserID = id.Value; //You do not need it here
if(viewModel != null)
return View(viewModel);
}
return RedirectToAction("UsersListPage");
}
UPDATE #1
Controller:
public ViewResult Index(){
return View(db.Users.ToList());
}
View:
#model IEnumerable<YourNamespace.User>
#foreach (var user in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => user.UserName)
</td>
</tr>
}
Isn't this working for you?

Using a foreign key in dropdown in mvc

I'm new to MVC, and stuck on what should be a pretty straight forward issue. I'm working through this tutorial and got everything pretty much working, except I now want to add a foreign key 'link' (not sure what it's called) but can't seem to get it to work. Here's what I have:
Tables:
Inventory:
Id | SerialNumber | ManufacturerId (foreignkey to Manufactueres->id)
Manufactureres
Id (primary key) | Name
Model (InventoryItem.cs):
public class InventoryItem {
public int Id {get; set; }
public int SerialNumber{ get; set; }
//this starts the trouble, I actually want to interact with the Manufactureres table -> Name column
public int ManufacturerId { get; set; }
}
View (Create.cshtml):
...
//What i really want is a dropdown of the values in the Manufactureres table
#Html.EditorFor(model=> model.ManufacturerId)
This must be a farely common issue when using a relational database there would be many foreign key relationships to be used/shown, but for some reason i can't find a tutorial or issue on stackoverflow that directly corresponds to something so simple. Any guidance, or direction is much appreciated!
Thanks,
I hope I understand your question correctly. Seems like when you want to add a new inventory item then you want a list of all the manufacturers in a dropdown list. I am going to work on this assumption, please let me know if I am off the track :)
Firstly go and create a view model. This view model you will bind to yout view. Never bind domain objects to your view.
public class InventoryItemViewModel
{
public int SerialNumber { get; set; }
public int ManufacturerId { get; set; }
public IEnumerable<Manufacturer> Manufacturers { get; set; }
}
Your domain objects:
public class InventoryItem
{
public int Id { get; set; }
public int SerialNumber{ get; set; }
public int ManufacturerId { get; set; }
}
public class Manufacturer
{
public int Id { get; set; }
public string Name { get; set; }
}
Your controller might look like this:
public class InventoryItemController : Controller
{
private readonly IManufacturerRepository manufacturerRepository;
private readonly IInventoryItemRepository inventoryItemRepository;
public InventoryItem(IManufacturerRepository manufacturerRepository, IManufacturerRepository manufacturerRepository)
{
// Check that manufacturerRepository and inventoryItem are not null
this.manufacturerRepository = manufacturerRepository;
this.inventoryItemRepository = inventoryItemRepository;
}
public ActionResult Create()
{
InventoryItemViewModel viewModel = new InventoryItemViewModel
{
Manufacturers = manufacturerRepository.GetAll()
};
return View(viewModel);
}
[HttpPost]
public ActionResult Create(InventoryItemViewModel viewModel)
{
// Check that viewModel is not null
if (!ModelState.IsValid)
{
Manufacturers = manufacturerRepository.GetAll()
return View(viewModel);
}
// All validation is cool
// Use a mapping tool like AutoMapper
// to map between view model and domain model
InventoryItem inventoryItem = Mapper.Map<InventoryItem>(viewModel);
inventoryItemRepository.Insert(inventoryItem);
// Return to which ever view you need to display
return View("List");
}
}
And then in your view you might have the following:
#model MyProject.DomainModel.ViewModels.InventoryItems.InventoryItemViewModel
<table>
<tr>
<td class="edit-label">Serial Number <span class="required">**</span></td>
<td>#Html.TextBoxFor(x => x.SerialNumber, new { maxlength = "10" })
#Html.ValidationMessageFor(x => x.SerialNumber)
</td>
</tr>
<tr>
<td class="edit-label">Manufacturer <span class="required">**</span></td>
<td>
#Html.DropDownListFor(
x => x.ManufacturerId,
new SelectList(Model.Manufacturers, "Id", "Name", Model.ManufacturerId),
"-- Select --"
)
#Html.ValidationMessageFor(x => x.ManufacturerId)
</td>
</tr>
</table>
I hope this helps :)
Yes, this is common issue, you need select Manufactureres in action and then send them to view. You can use ViewBag or strontly typed view model.
Examples:
Problem populating dropdown boxes in an ASP.NET MVC 3
Application
Having difficulty using an ASP.NET MVC ViewBag and
DropDownListfor
MVC3 Razor #Html.DropDownListFor
This is what I would recommend you.
1) Create a Manufacturer model class
public class Manufacturer
{
public int Id { get; set; }
public string Name { get; set; }
}
2) Create InventoryItem model class as follows
public class InventoryItem
{
public int Id { get; set; }
public int SerialNumber{ get; set; }
public int ManufacturerId { get; set; }
[ForeignKey("Id ")]
public Manufacturer Manufacturer{get; set;}
public IEnumerable<Manufacturer> Manufacturer {get;set;}
}
3) Make sure DbContext is also updated as follows
public DbSet<InventoryItem> InventoryItem {get;set;}
public DbSet<Manufacturer> Manufacturer{get;set;}
4) Controller
[HttpGet]
public ActionResult Create()
{
InventoryItem model = new InventoryItem();
using (ApplicationDbContext db = new ApplicationDbContext())
{
model.Manufacturer= new SelectList(db.Manufacturer.ToList(), "Id", "Name");
}
return View(model);
}
[HttpPost]
public ActionResult Create(InventoryItem model)
{
//Check the Model State
if(! ModelState.IsValid)
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
model.Manufacturer= new SelectList(db.Manufacturer.ToList(), "Id", "Name");
return View(model);
}
}
using (ApplicationDbContext db = new ApplicationDbContext())
{
InventoryItem dto = new InventoryItem();
dto.SerialNumber= model.SerialNumber;
dto.Id= model.Id;
Manufacturer manudto = db.Manufacturer.FirstOrDefault(x => x.Id== model.Id);
dto.CatName = manudto.CatName;
db.Test.Add(dto);
db.SaveChanges();
}
TempData["SM"] = "Added";
return RedirectToAction("Index");
}
5) Make sure View has dropdownselect option in below format
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Id, Model.Manufacturer,"Select", new { #class = "form-control" } )
#Html.ValidationMessageFor(model => model.Id, "", new { #class = "text-danger" })
</div>
</div>
Hope this works :D

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);

Resources