0

I have two tables - Prm_Staff and Prm_Salutation - one of which holds staff names and a salutation ID, the other lists the salutations. Their models are such:

public class Prm_Staff
{
    public int ID { get; set; }
    public int SalutationID { get; set; }
    public string FName { get; set; }
    public string LName { get; set; }
    public bool Active { get; set; }

    //method to insert data
    public Prm_Staff(int id, int salID, string fname, string lname, bool active)
    {
        ID = id;
        SalutationID = salID;
        FName = fname;
        LName = lname;
        Active = active;
    }

    //parameterless constructor
    public Prm_Staff() { }
}

public class Prm_Salutation
{
    public int ID { get; set; }
    public string Desc { get; set; }
    public bool Active { get; set; }

    public Prm_Salutation(int id, string desc, Boolean active)
    {
        ID = id;
        Desc = desc;
        Active = active;
    }

    public Prm_Salutation() { }
}

I wish to have a View that has

  • A form to insert new staff members, with a dropdown of active salutations
  • Another form beneath it that lists all current staff members in editable fields, with a dropdown of salutations for each (with the default value equaling that row's Salutation ID).

I have built a view that fulfils the above, using a linq query to pass the Salutation data to the view via ViewData. I wish to know however how to establish a foreign key relationship, and then how to create a ViewModel that combines the necessary information and will pass it to the View in one go, as apparently that this is the proper way to achive what I'm doing.

I know I might come accross cheeky, but please, when answering use the simplest possible terms. I am self taught, so terminology you find second nature can be Vulcan to me. Also include any 'using: ...' statements, and be clear as to where any code examples are to be placed.

5
  • Did you create the DataBase? Using Entity Framework or something else? (With the foreign key) Commented Dec 4, 2013 at 15:15
  • Yes, I created a database using Entity Framework. The tables created no problem, and Create / Edit / Delete no problem. I created a foreign key, but I don't think I did so correctly, so ommitted it here to see what the correct format was. Commented Dec 4, 2013 at 15:37
  • 1
    ok that's why I asked. First of all you should be sure that the foreign key was created correctly. To be sure, delete the database and start the process again using EntityFramework Code First Migration, you can use this tutorial asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/…. On the other hand to ensure the proper foering key creation I would recommend you to do this in your model classes pastie.org/8528445 Let me know. Commented Dec 4, 2013 at 15:51
  • @Guillelon I added the suggested lines (The salutation reference in the staff table is actually what I had, but not the reference in the salutation tbl). Running the code now, it works fine for CRUD - without using dropdowns (inputting a salutation ID value manually via text field). Can I ask what exactly the supplied lines do? I thought just create a reference, but I see you using List<>... Commented Dec 4, 2013 at 16:18
  • It's like a over do for Entity Framework understand the relations you wanted to have. Now that you have a correct foreign key I'll be writing a proper answer to help you. Commented Dec 4, 2013 at 16:35

1 Answer 1

1

A form to insert new staff members, with a dropdown of active salutations

I'd do it this way.

ViewModel:

public class Prm_Staff_View_Model
{
    public int ID { get; set; }
    public string FName { get; set; }
    public string LName { get; set; }
    public bool Active { get; set; }
    //The selected One
    public int SelectedSalutationID { get; set; }
    //The list with the salutations availables
    public List<Prm_Salutation> AvailableSalutations{get;set;} 

    public Prm_Staff() { }        
}

Controller GET method:

    // GET: /Create
    public ActionResult Create()
    {
        var staffCreateViewModel = new Prm_Staff_View_Model();
        staffCreateViewModel.AvailableSalutations = new List<Prm_Salutation>();
        //Here you get the salutations that want to display in the dropdown
        staffCreateViewModel.AvailableSalutations = context.getMySalutations();
        return View(staffCreateViewModel);
    } 

View: using the HTML extension DropDownListFor, we can do this:

@Html.DropDownListFor(model => model.SelectedSalutationID, Model.AvailableSalutations.Select(option => new SelectListItem {
    Text = Html.DisplayTextFor(_ => option.Desc ).ToString(), //Text shown in the DropList
    Value = option.ID.ToString(), //Value taken
    Selected = (Model != null) && (option.ID == Model.SelectedSalutationID) //If you're gonna edit the staff member, the selected salutation is the one that already has. 
}), "Choose...")

Controller POST method:

[HttpPost]
public ActionResult Create(Prm_Staff_View_Model viewModel)
{
   //Here you map your viewModel against the model and save it. 
   var myModel = new Prm_Staff();
   myModel.SalutationID = viewModel.SelectedSalutationID;
}

For mapping object I suggest the Nuget library AutoMapper , or you can do it manually. Let me know.

Sign up to request clarification or add additional context in comments.

8 Comments

This is fantastic. I have questions, but I need to finish for tonight. I will try the code and play around with it in the morning and get back to you?
@Eamonn yeah don't worry, just let me know ;) glad to help
I have pasted the entire existing ViewModel, Controller and View to codepad. There are a few errors thrown: The VM requires a return type, and the View does not recognise the definitions for AvailableSalutations or SelectedSalutationID. There are some type inferral errors too, but I imagine they will dissapear when the VM is inherited correctly. Once I get it working, I would like to ask you one or two questions about what exactly is happening - if you dont mind! :)
Ok, in the code you sent me the View is receiving a List of Staff_Salutation_VM, so in order to recognize AvailableSalutations or SelectedSalutationID it should receive just one object or when you call the DropDownListFor use in the for something like this model => model[i].SelectedSalutationID. When you say that the VM requires a return type, you need to be a little bit more specific. So let me know ;)
Thanks man - the return type issue is in the ViewModel with the line public Prm_Staff() { } which throws Method must have a return type. As for the List<November.ViewModels.Staff_Salutation_VM>, do I not need a numerable to iterate through to get all my Prm_Staff rows?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.