Get field from different model in MVC 5 - asp.net-mvc

I have a model linked to a second table:
public class Rock
{
public int ID { get; set; }
[ForeignKey("Con")]
public int ConID { get; set; }
public virtual Con Con { get; set; }
}
public class Con
{
public int ID { get; set; }
public virtual ICollection<Rock> Rock{ get; set; }
[Required]
[RegularExpression(#"^[0-9A-Za-z '']+$")]
[StringLength(200, MinimumLength = 3)]
public string Name { get; set; }
}
In my control, I have a 'create' action:
// GET: Rock/Create/3337
[Route("Rock/Create/{ConID?}")]
public ActionResult Create(int? ConID)
{
var rock= new Rock();
rock.ConID = (int)ConID;
return View(rock);
}
I'd like to get the con name from that table and send it to the view. At this point it doesn't know the name because there's no 'rock' record linking it yet.
Any suggestions? Thanks in advance!

If you have created a strongly typed view with Rock as Type, you need to either add 'Con Name' property to Rock Type or else you need to create a new Type and add the data to this Type which you want to pass to the View.
public class NewType
{
public int ConID { get; set; }
public string ConName { get; set; }
}
Add the data you want to pass in this Type and return view with this object:-
public ActionResult Create(int? ConID)
{
var newType= new NewType();
newType.ConID = (int)ConID;
newType.ConName = "XYZ";
return View(newType);
}

The two suggestions I would give are to pass Con.name to the view in the viewbag or to create a viewmodel, as Rahul suggested, that combines the properties of different classes that are needed for that particular view.

Related

MVC Controller to Controller data

Is there a way in MVC to pass information from one controller to another? I have a character model that looks like this:
public class Character
{
[Key]
public string CharacterID { get; set; }
public string UserID { get; set; }
public string Name { get; set; }
public int Str { get; set; }
public int Con { get; set; }
public int Dex { get; set; }
public int Int { get; set; }
public int Wis { get; set; }
public int Cha { get; set; }
public int BaseAttack { get; set; }
}
And a separate weapon model like this:
public class Weapons
{
[Key]
public string WeaponID { get; set; }
public string UserID { get; set; }
public string CharacterID { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public string Range { get; set; }
public int Damage { get; set; }
public int Crit { get; set; }
public int CritMultiplier { get; set; }
public string Hands { get; set; }
public string Distance { get; set; }
}
To create a weapon, you first need to create a character which assigned an ID, and I want to be able to pass that ID into the create method of my weapon controller. Is there a way to do this? Thanks
You can use TempData for this purpose. TempData stores data only between two requests. When you set the TempData the next request that is initiated can retrieve value from the TempData and it will be erased for any consequent requests.
[HttPost]
public ActionResult CreateCharacter()
{
// creates charaeters here and sets the tempdata
TempData['CharacterId'] = 50;
return RedirectToAction('CreateWeapon');
}
[HttpGet]
public ActionResult CreateWeapon()
{
var weaponModel = new WeaponModel() { CharacterId = (int)TempData['CharacterId'] };
return View(weaponModel);
}
and in your view simply have a hidden for the CharacterId, so it will be persisted if you your post fails validation or if you need to re-display the view.
#Html.HiddenFor(e => e.CharacterId);
Again this is just one approach, only if you you don't want to pass the CharacterId in the url.
You can also achive this just by passing it in the url:
[HttPost]
public ActionResult CreateCharacter()
{
// creates charaeters here and sets the tempdata
return RedirectToAction('CreateWeapon', new { characterId = 50 });
}
[HttpGet]
public ActionResult CreateWeapon(int characterId)
{
var weaponModel = new WeaponModel() { CharacterId = characterId };
return View(weaponModel);
}
I would be inclined to pass the character id to the create weapon action via routing, either as a route token that forms part of the path or via the query string. Be sure to check that the weapon can logically be associated with the character to whom the id corresponds.
You could also pass the id using TempData or Session, but considering both by default will take up memory on the web server, the simple option is to use the routing. In addition, unless you call TempData.Keep("key") after accessing TempData, the value will be removed from TempData after the first access, potentially causing issues if the user refreshes the browser window.
You could use RedirectToAction(), though as titled this will cause browser redirection.
return RedirectToAction("CreateWeapon", "Weapon", new { id = yourid });
or
#Html.ActionLink("CreateWeapon", "Create", new { id = yourid })
Edit: Your plain object property names and your action method variables need to match, to do this.

How to pass two LINQ joined tables from Controller to View

I have three objects:
public class Part
{
[Key]
public int ID { get; set; }
public string Number { get; set; }
public string Name { get; set; }
public int descID { get; set; }
}
public class Description
{
[Key]
public int descID { get; set; }
public string descName { get; set; }
public string description { get; set; }
}
public class GridPart
{
public string name{ get; set; }
public string number { get; set; }
public string description { get; set; }
}
I'm using LINQ to join Part and Description on the descID column:
public ActionResult Index()
{
var myParts = from p in db.Parts
join d in db.Description on p.descID equals d.DescriptorID
select new { Description = d.description, Name = p.name};
List<GridPart> partsList = new List<GridPart>();
foreach (var m in myParts)
{
GridPart gp = new GridPart();
gp.Name = m.name;
gp.description = m.description;
partsList.Add(gp);
}
return View(partsList);
}
If I was just using the Parts table, in the view I would do:
#model IEnumerable<MyApp.Models.Part>
What do I do if I'm using the joined table? This uses both Parts and Description, not to mention my List of GridParts, how do I pass this through to display all of the data I need?
Any advice is greatly appreciated.
If you pass an anonymous type to your view it won't be strongly typed. You can refer to your model like this instead
#Html.TextBox("Name")
or
#Html.Display("Name")
Although this will work I would advice against it - The better solution would be to go with a Viewmodel instead. This will make your view strongly typed.
Edit: Looking on this again I see that your actually not parsing the anonymous type to your view. Your parsing a list of GridParts.
You should be able to strongly type your view like your tried - just refer to GridParts instead of parts.
#model IEnumerable<MyApp.Models.GridPart>

Saving many to many relationship tables in Asp.Net MVC

I use Asp.Net MVC, Entity Framework. I have a form it looks like below.
Here, dropdownlist is filled from a table(types). Checkboxes is filled from another table(test). Tables are like below:
public class Types
{
public int TypesID{get;set;}
public string TestName { get; set; }
public string TestExplanation { get; set; }
public int TestTime { get; set; }
}
public class Tests
{
public int TestID{get;set;
public string Name { get; set; }
public string Code { get; set; }
}
public class Types_Tests
{
public int Types_TestsID{ get; set; }
public int TypesID { get; set; }
public int TestsID { get; set; }
public virtual Types Types { get; set; }
public virtual Tests Tests { get; set; }
}
Types_test table is relation table between Types and Tests. When I click Kaydet button, it shuld save type and checked tests. I made this operation using ViewBag, javascript and hdnvalue.I added checked checkboz values to a hdntext. I made saving process like below:
[HttpPost]
public ActionResult Index(string drpType, string hdntesttypes)
{
var TypeList = Types.GetAll();
ViewBag.TypesList = new SelectList(TypeList, "Id", "Name");
var testypeList = testTypes.GetAll();
ViewBag.TestTypesList = new SelectList(testypeList, "Id", "TestName");
GenericRepository<TestDisabledTypes> testDisabledRepository = new GenericRepository<TestDisabledTypes>(_context);
if (!string.IsNullOrEmpty(hdntesttypes))
{
string[] disabletypesArray = hdntesttypes.Split(',');
using (TransactionScope trns = new TransactionScope())
{
for (int i = 0; i < disabletypesArray.Length; i++)
{
Test_Types types = new Test_Types ();
types.TestTypesID = Convert.ToInt32(disabletypesArray[i]);
types.TypesID = Convert.ToInt32(drpType);
testDisabledRepository.Insert(types);
}
trns.Complete();
}
}
return View();
}
It wokrs. But I search better solution for this process. Can someone give me any idea?
Thanks.
If you don't need additional attributes for your entity class, you don't need create link table.
Just define the following class, and EF will generate the link table for you automatically.
public class Type
{
public int TypesID{get;set;}
public string TestName { get; set; }
public string TestExplanation { get; set; }
public int TestTime { get; set; }
public ICollection<Test> Tests { get; set; }
}
public class Test
{
public int TestID{get;set;
public string Name { get; set; }
public string Code { get; set; }
public ICollection<Type> Types {get;set;}
}
Well, in EntityFramework if you want to create a many to many relation object you need to create new object of "linking" entity. Unfortunately, it is not possible to add first object, add second object and say "Guys, you are in many to many relationships. Are you happy then?" :) You need to create relation object, set appropriate fields in it (I think these are ids of two objects itself) and add it to relation collection (entity) in your model. But before doing so you need to be sure that objects with data you are linking with are already exists in database. Otherwise you'll get an error
Also it's not necessary to create manually transaction because EF does it for you automatically each time you get/save your data

ASP.NET MVC What is the best way to use ViewModels?

Customers.cs
public partial class Customers
{
public int sno { get; set; }
public string CustomerName { get; set; }
public string CustomerNo { get; set; }
...
// 20 more attribute too...
}
Cities.cs
public partial class Cities
{
public int sno { get; set; }
public string CityName { get; set; }
public string CityPlate { get; set; }
public string CityPhoneCode { get; set; }
}
AddCustomerViewModel.cs
public class AddCustomerViewModel
{
[Required(ErrorMessage = "Şehir seçiniz.")]
[Display(Name = "Şehir")]
public Nullable<int> CityId { get; set; }
// same with Customers.cs
public int sno { get; set; }
[Required(ErrorMessage = "Müşteri adını giriniz!")]
[Display(Name = "Müşteri Adı")]
public string CustomerName { get; set; }
[Required(ErrorMessage = "Müşteri numarası giriniz!")]
[Display(Name = "Müşteri Numarası")]
public string CustomerNo { get; set; }
...
// 20 more attribute too...
}
Controller
[Authorize(Roles = "Administrator")]
public ActionResult AddCustomer()
{
AddCustomerViewModel addCustomerViewModel = new AddCustomerViewModel();
addCustomerViewModel.Cities = entity.Cities;
return View(addCustomerViewModel);
}
[HttpPost]
[Authorize(Roles = "Administrator")]
public ActionResult AddCustomer(AddCustomerViewModel addCustomerViewModel)
{
entity.Customers.Add(GetCustomerFromViewModel(addCustomerViewModel));
entity.SaveChanges();
return View(addCustomerViewModel);
}
I m using a function that is called GetCustomerFromViewModel to convert addCustomerViewModel to Customer like below:
GetCustomerFromViewModel()
private Customers GetCustomerFromViewModel(AddCustomerViewModel addCustomerViewModel)
{
Customers customer = new Customers();
customer.CityId = addCustomerViewModel.CityId;
customer.CreatorUserId = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey;
customer.CustomerName = addCustomerViewModel.CustomerName;
customer.CustomerNo = addCustomerViewModel.CustomerNo;
customer.Description = addCustomerViewModel.Description;
...
// 20 more attribute too...
return customer;
}
But Customers class have too many variable (customerNo, CustomerName, ...) , So this is the not good way.
When I use DbContextGenerator and Add classes to dataAnnotations and then When I udated the model, dataAnnotations is deleted. (Because DbContext classes are updated, too)
How Can I use ViewModels with DataAnnotations. And effective insert operation to Db? Article, Tutorial, example or advice?
I hope I can explain.
Thanks a lot...
You may take a look at AutoMapper which will simplify the mapping logic between your domain models and view models so that you don't need to manually map each property. Other than that there's nothing wrong with your code. You are already using a view model and have a mapping layer. So your GetCustomerFromViewModel function might become:
private Customers GetCustomerFromViewModel(AddCustomerViewModel addCustomerViewModel)
{
return Mapper.Map<AddCustomerViewModel, Customers>(addCustomerViewModel);
}
or completely get rid of it and directly use the AutoMapper call in your controller action because this function no longer brings much value:
[HttpPost]
[Authorize(Roles = "Administrator")]
public ActionResult AddCustomer(AddCustomerViewModel addCustomerViewModel)
{
var customer = Mapper.Map<AddCustomerViewModel, Customers>(addCustomerViewModel);
entity.Customers.Add(customer);
entity.SaveChanges();
return View(addCustomerViewModel);
}

Mapping with automapper

I have a domain model:
public class Project
{
[Key]
public int ProjectID { get; set; }
public string Title { get; set; }
public string Slug { get; set; }
public string Content { get; set; }
public string Category { get; set; }
public string Client { get; set; }
public int Year { get; set; }
}
I have a view model (which is a portion of the above model):
public class ListProjectsViewModel
{
public IEnumerable<ProjectStuff> SomeProjects { get; set; }
public class ProjectStuff
{
public int ProjectID { get; set; }
public string Title { get; set; }
public string Slug { get; set; }
public string Content { get; set; }
}
// Some other stuff will come here
}
I have an action controller:
public ActionResult List()
{
// Get a list of projects of type IEnumerable<Project>
var model = m_ProjectBusiness.GetProjects();
// Prepare a view model from the above domain entity
var viewModel = Mapper.Map..........
return View(viewModel);
}
How can I code the mapping '........' with automapper ?
Thanks.
There are two steps.
1) Define a mapping with AutoMapper (this is usually done in some sort of bootstrapper called by Global.asax, etc.)
// since all of your properties in Project match the names of the properties
// in ProjectStuff you don't have to do anything else here
Mapper.CreateMap<Project, ListProjectsViewModel.ProjectStuff>();
2) Map the object in your controller:
// Get a list of projects of type IEnumerable<Project>
var projects = m_ProjectBusiness.GetProjects();
// Prepare a view model from the above domain entity
var viewModel = new ListProjectsViewModel
{
SomeProjects = Mapper.Map<IEnumerable<Project>, IEnumerable<ListProjectsViewModel.ProjectStuff>>(projects)
};
return View(viewModel);
The thing to note here is that you are defining a mapping between Project and ProjectStuff. What you are trying to map is a list of Projects (IEnumerable) to a list of ProjectStuff (IEnumerable). AutoMapper can do this automatically by putting that in the generic arguments as I did above. Your View Model that your view is using is wrapping your list of ProjectStuff, so I just create a new ListProjectsViewModel and do the mapping inside of that.

Resources