I'm working on an application that manages people and their spouses, if married. Essentially a person will be entered and then from that person I want to be able to add a spouse. My database schema is like this. Persons (Person_ID, Name, BirthDate, etc...), Marriages(Marriage_ID, Husband_ID, Wife_ID, Date).
The process is Add a Person then, if married, add spouse. So I have a Person Controller with an ADD action (get and post). When Add Spouse is selected in the Details view the AddSpouse Action is called which will create the new person (spouse) and then create the marriage. MY issue is that I need to pass the PersonID of the original person to the AddSpouse action in order to create a marriage. What is the best way to do that?
You can pass your personID in ViewData like this :
ViewData["PersonID"] = 1
and recover it in AddSpouse action
var id = ViewData["PersonID"]
Related
I have 2 domain classes
Expenditure
class Expenditure {
Date date
Supplier supplier
String particular
BigDecimal amount
}
Supplier
class Supplier {
String name
String address
static hasMany = [expenditures: Expenditure]
}
What happening is that when I create a new expenditure, I will enter the supplier from the list of suppliers in the Supplier class. When the supplier is not exist, I will have to create it first and then select it when creating the expenditure.
What I want is that, when I enter the supplier it will be looked up, and when not found, it will be created on the go (when saving the expenditure instance) without me having to create it first in the Supplier table and then come back to Expenditure to complete the form.
How can I achieve this?
What I want is that, when I enter the supplier it will be looked up,
and when not found, it will be created on the go
One option you have is to do something like one of these...
Supplier.findOrCreateByName('some name goes here')
Supplier.findOrCreateByNameAndAddress('some name goes here', 'some address goes here')
There are also findOrSaveBy... counterparts but those only work if you are supplying enough search criteria to create a fully save-able instance.
I hope that helps.
I am trying to learn mvc - I apologize in advance for all the silly questions. What I've done is created an mvc proejct based on an exsiting database, and then i've been disecting it to try to understand what's been created for me, and how to create my own stuff. Unfortunately, because I'm a new stackoverflow user, i can't post a picture of my project structure.
i have a parent controller and a child controller created using the wizard based on 2 separate tables i have in my model. I want to display both of them in one view - ultimately in a webgrid and be able to change data for any parent item, or child item. You can ignore the CombinedController for now. I've been doing some reading and i've learned that i should be creating a viewmodel that combines both the parent and child at the model level, and then go from there.
so i created this class:
Imports System.Data.Objects.DataClasses
Public Class ParentAndChild
Public Property myChildren As IEnumerable(Of Child)
Public Property myParent as Parent
End Class
I have a few questions:
Question 1
Do i have to add this ParentAndChild entity into the .edmx file in order to create a controller and view for it? I guess what I'm really asking is do i have to create a view in the sql database first, have the entity show up in the .edmx and then create a controller? Or can I just combine the two entities in a class? That's what i've done so far. I don't have a sql View in my database combining these two tables. The reason why I ask is because when i create my controller, if i want to get all the CRUD for free, i have to create using the Entity Framework. But I don't know what to specify for the data context.
Question 2
If i want a webgrid to somehow show all my parents and all their children, will the new ParentAndChild class work? I think that will only show the details for One parent and its children. I think i need to create a list of parents.. and then in the parentlist for each parent, add a collection of modules. But i don't know how to do this..
Question 3
How does the entityframework know which modules to return when i'm using my new class? I don't define the relationship anywhere... Is it because in the .edmx file, the system knows the relationships between the tables?
If you simply need to access the information of a parent entity and its child entity's you should be able to send your view the parent entity. A ViewModel is not absolutely necessary for this if Entity Framework knows about the relationship between the two entity's. If the relationship between the 2 tables exists at the database level then Entity Framework should have modeled it automatically.
An example of a controller would be:
public ActionResult Parent(int id)
{
var parent = context.Foo.Single(x => x.Id == id);
return View(parent);
}
If you need to create a table of all the child entity's you could do something like this:
#foreach(var item in Model.Children)
{
<td>#item.Property</td>
<td>#item.Property2</td>
}
I have a model, called Organisation and the model is stored in an assembly called Model. There is a requirement to insert an organisation and update an organisation.
Couple of questions:
When inserting a new organisation, I want to ensure that the organisation doesn't already exist so I've inserted some remote validation. I then bind the model to the insert view.
Now, when I'm creating the update view should I use a different view model which removes the remote validation for duplicate organisation names? If so, I can't use my base Organisation model for the update view, so do I then need to create 2 different views, one for insert and one for update? If this is the case, there is going to be 2 views that are basically the same but just use different models.
Can anyone help?
For this specific scenario the validation that no other organization with the same name exists seems valid for both the insert and update case so you could reuse the same view model.
However validating that the name does not exists when updating a organization must have extra because if the user does not change the organization name then at least one record on the database has that name, the one being updated, and the validation should ignore that record.
So if you choose to reuse the view model the validation must perform according to the context of the operation (insert or update).
Question 1: check validation:
If their is something not valid, do this:
If(isNotValid()){
ModelState.AddModelError("Key", "The user name or password provided is incorrect.")
}
Key is the field in your view that is incorrect.
Question 2: Difference between Create / Edit
You should use the same ViewModel, because in your update, they can still change the "Organisation Name" and you should still check if it is unique.
But why should you use a ViewModel just to check the validation? Is there a reason why you can't check the organisation names for uniqueness in your controller and do a ModelState.AddModelError when it is not unique?
A ViewModel is when you have to extend the Page, For Example
public class DashBoardViewModel
{ public List(Of Organisation) Organisation {get;set;}
public List(Of Staff) Staff{get;set;}
public List(Of Assignment) Assignments{get;set;}
}
Above would be a fictional DashBoardViewModel where i show all the Organisations, Staff and Assignments.
A ViewModel doesn't contain just one type of object, it contains multiple.
And don't forget, sometimes when you need to add some data to a View, you could just use ViewData or ViewBag, instead of creating a ViewModel.
I am absolutely new to the MVC application.I want a dropdown list on my form I have done it this way
"<%= Html.DropDownList("Categories", (IEnumerable<SelectListItem>)ViewData["Categories"])%>"
I am sending the viewdata[Categories] from the controller class file.
this way
IList allCategories = _dropdownProvider.GetAllCategories();
ViewData["Categories"] = new SelectList(allCategories, "catid", "catname");
Now my requirement is that when the user selects a particular category from the dropdownlist its id should get inserted in the database,
The main problem is category id I want to insert the category id in the product table where the category Id is the foreign Key.
Please tell me how can I do this.
Normally you would do the following:-
On your view you would have...
Inherits="System.Web.Mvc.ViewPage<Product>" THIS IS A REFERENCE TO YOUR PRODUCT ENTITY
and in the page you can do this...
Category <%=Html.DropDownList("CatId") %>
you would also have the GET controller which defines the list
public ActionResult Add()
{
ViewData["CatId"] = new SelectList(allCategories, "catid", "catname");
then you can get the CatId from the product passed in to the Add method
e.g.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add(Product product)
{
int catId = product.CatId
HTH. You ought to buy a book on the subject as MVC takes away alot of the pain of binding from you.
when you try to post the view, you'll have a "Categories" key in your querystring. you could convert it to long or the type you use in your table and set it to the product instance that you want to.
if this is not so clear, please send your code for a better explanation.
If i Understand right your question, the only thing you have to do, is inspect the POST for the "Categories" Key, and it will contain the selected value of the DropDownList.
var selectValue = System.Convert.ToInt16(Request.Form["name"]);
Or if you use ModelBinder and define a model that bind that value directly, you just have to Update the Model with
bool x = TryUpdateModel(YourModelNameHere);
This will automatically inspect the current ControllerĀ“s Value Provider and bind that value to the corresponding property in your model.
I recoment you to use the parameter FormCollection in your controller, and put a breakpoint, you can see all the values send within the POST. All that values are accessible through Request.Form["KEY"].
At the table level I'm setting aspnet_User.UserID as foreign key of UserID in the other tables (like Posts.UserID, so each post has an owner). Is that the way to go?
When I create the LINQ to SQL model, should I include the aspnet_User table?
When I create a post (record in the Posts table, a Post object), how do I set the relationship to the logged in user (User object in the controller)?
I don't include the aspnet_User table to my linq-to-sql as I don't really need it. I use the built in way of accessing membership data.
But for your table Posts, it might be easier for you to include it so that you can easily display the User's Name by doing myPost.User.Name
edit:
MembershipUser user = Membership.GetUser();
Guid userGuid = (Guid)user.ProviderUserKey;
Post post = new Post
{
UserId =userGuid,
Message = message
};
In your database schema, you should definately have a the UserID in the Post table be a foreign key to the aspnet_user table, on the UserID field. This way, you are making sure your data is clean. I would even add a cascade delete & update on that relationship.
Then, refer to my instructions in a previous question you asked, about how to get the user data.
(Thomas Stock summed it up briefly, above, though :) )