1

I have two classes where one is a parent class for the other. The basic CRUD functions was created in the controller. In the design of my table I have the parent id in my child class as the foreign key. In the view for Create function of the child, I am asked to enter the parent ID. I have changed the Create to accept the ID of the parent. But when I remove the code for selecting the parent id in the view I get exception in my Create. Is there a way I can set the parent ID in both my create functions(Over loaded functions).

    public ActionResult Create(int? id)
    {
        ViewBag.LsystemID = new SelectList(db.Lsystem, "LsystemID", "LsystemName",id);
        ViewBag.TCID = new SelectList(db.TC, "TCID", "TCName");
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "OptionID,OptionName,TCID,LsystemID")] Option option)
    {
        if (ModelState.IsValid)
        {
            db.Option.Add(option);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

    //    ViewBag.LsystemID = new SelectList(db.Lsystem, "LsystemID", "LsystemName", op);
        ViewBag.TCID = new SelectList(db.TC, "TCID", "TCName", option.TCID);
        return View(option);
    }

View

@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.LabelFor(model => model.OptionName, htmlAttributes: new { @class = "control-label col-md-2" })
    @Html.EditorFor(model => model.OptionName, new { htmlAttributes = new { @class = "form-control" } })
    @Html.ValidationMessageFor(model => model.OptionName, "", new { @class = "text-danger" })

    @Html.LabelFor(model => model.TCID, "TCID", htmlAttributes: new { @class = "control-label col-md-2" })
    @Html.DropDownList("TCID", null, htmlAttributes: new { @class = "form-control" })
    @Html.ValidationMessageFor(model => model.TCID, "", new { @class = "text-danger" })

    @Html.LabelFor(model => model.LsystemID, "LsystemID", htmlAttributes: new { @class = "control-label col-md-2" })
    @Html.DropDownList("LsystemID", null, htmlAttributes: new { @class = "form-control" })
    @Html.ValidationMessageFor(model => model.LsystemID, "", new { @class = "text-danger" })

    <input type="submit" value="Create" class="btn btn-default" /> 
}

How can I pass the value LsystemID without being shown in the View?

EDIT 1 : Adding Model class

 public class Lsystem
{
    public int LsystemID { get; set; }
    public string LsystemName { get; set; }
    public virtual ICollection<Option> Options { get; set; }
  //  public int OptionId { get; set; }

}

public class Option
{
    public int OptionID { get; set; }
    public string OptionName { get; set; }
    public int TCID { get; set; }
    public virtual TC tc { get; set; }
    public virtual Lsystem Lsystem { get; set; }
    public int LsystemID { get; set; }
    public virtual ICollection<OptionValue> OptionValues { get; set; }
}
tereško
  • 58,060
  • 25
  • 98
  • 150
Vini
  • 1,978
  • 8
  • 40
  • 82
  • What is the model in the view? Assuming its `Option`, does it have a property for the 'parentID`? –  Sep 25 '15 at 07:54
  • Class added.. Model in the view is Option. I did not want the code to be so long. @StephenMuecke – Vini Sep 25 '15 at 07:58
  • You need to give some clues :). I assume `LsystemID` is the parent? In which case in the GET method you need to initialize a new `Option` and set `LsystemID = id`, then return the model to the view (but I'm not sure why you then need a dropdown for it) –  Sep 25 '15 at 08:01
  • And you need to start learning to use view models. Because the data model contains `virtual Lsystem` and `virtual TC` this will all start failing if any of the properties of those types contain validation attributes. –  Sep 25 '15 at 08:03
  • But in my case i need all the values to be set. So why should i use a viewmodel? Its just that i did not mention the scenario along with TC – Vini Sep 25 '15 at 08:05
  • How do you think all the values of either `Lsystem` or `TC` could be set in the view? - you only have dropdownlists for them! –  Sep 25 '15 at 08:06
  • I only want the value for the LsystemID to be set in the program. Its because this function is called from the Lsystem View. There I pass the value of the LsystemID to the create function. I am looking for a way to actually bind the value in my create function rather than giving an option to edit it in the UI. – Vini Sep 25 '15 at 08:07
  • I am not sure if my understanding is right. The values entered by the user are passed to the controller in the overloaded create function and then stored.. So in my situation i dont want the view to accept values for LSystemID. I have explicitly mentioned the value for the dropdownlist. – Vini Sep 25 '15 at 08:09
  • You have a bit to learn yet. Can I assume that `LsystemID` is the parent and you only need to enter `OptionName` and select the `TCID` in the dropdownlist in the view? –  Sep 25 '15 at 08:09
  • But i have tried `disable` to disable the dropdownlist which i found somewhere in SO. But that did not work for me. But i really do not want that to be displayed in my UI. rather I want the system to store the value and pass it to the controller – Vini Sep 25 '15 at 08:11
  • Yes.. Your assumption is right.. And I am on the process of learning and getting stuck with all this. Maybe it should have had a cleaner approach, but I could not think of any – Vini Sep 25 '15 at 08:12
  • OK thanks. May be I could give you a better look of my Datamodel. [http://programmers.stackexchange.com/posts/298138/revisions]this is my datamodel and this is what i want to achieve.. – Vini Sep 25 '15 at 08:14
  • Now i have disabled the Dropdownlist. But i am not able to remove that select list from my code# – Vini Sep 25 '15 at 08:18
  • 1
    In your view you can put `@Html.HiddenFor(x => x.LsystemID)` inside of your form and it will still be posted, you just need to provided the LsystemID in the get for the creation view – Canvas Sep 25 '15 at 08:27
  • That is the part i am missing now. I have added hiddenfor. but i am unable to set the value of theLSystemID in create.. I passed the value for SystemId in my other Create function. I don't think it could be accessed in the Get Create method. @Canvas – Vini Sep 25 '15 at 08:48
  • It can indeed, in your [HttpGet] method you can provide any parameters you like so for example you can put `public ActionResult Create(int parentId)` then in your link in the view to create you put something like this `Create`. your link will then go to the create method and also pass a value to parentId which will match on your get method. Then from your get method you provide that into your view by passing in a model or just a variable `return View(parentId)` which means model int. `@model int` in view – Canvas Sep 25 '15 at 08:52
  • But i have already passed my parentid to the create function. What i am missing now is the passingof parameter into my Create with bind options. Can i assign the value of ParentId in the view like `@Html.HiddenFor(model=>model.LsystemID)` and assign it to `@model.LsystemID = @model.id` – Vini Sep 25 '15 at 08:57
  • @ViniVasundharan I have created a small .NETfiddle for you which may help https://dotnetfiddle.net/JM3IM4 – Canvas Sep 25 '15 at 09:06
  • @canvas: i have changed my create method. But still it doesn't work – Vini Sep 25 '15 at 09:14
  • @Canvas: i have sorted it out. I had to pass the model to the view which i missed.. Thanks a lot for your comments. it really helped.. – Vini Sep 25 '15 at 09:31
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/90610/discussion-between-vini-vasundharan-and-canvas). – Vini Sep 25 '15 at 11:28

1 Answers1

1

Start by creating a view model representing what you need in the view (add validation and display attributes as required

public class OptionVM
{
  public int Lsystem { get; set; }
  public string Name { get; set; }
  public int TC { get; set; }
  public SelectList TCList { get; set; }
}

and in the controller

public ActionResult Create(int? id)
{
  OptionVM model = new OptionVM
  {
    Lsystem = id // set the parent
  };
  ConfigureViewModel(model);
  return View(model);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(OptionVM model)
{
  if (!ModelState.IsValid)
  {
    ConfigureViewModel(model);
    return View(model);
  }
  Option option = new Option
  {
    OptionName = model.Name,
    TCID = model.TC,
    LsystemID= model.Lsystem
  };
  db.Option.Add(option);
  db.SaveChanges();
  return RedirectToAction("Index");
}

private void ConfigureViewModel(OptionVM model)
{
  model.TCList = new SelectList(db.TC, "TCID", "TCName");
}

and in the view

@model OptionVM
@using (Html.BeginForm())
{
  @Html.AntiForgeryToken()
  @Html.HiddenFor(m => m.Lsystem)

  @Html.LabelFor(m => m.Name)
  @Html.TextBoxFor(m => m.Name)
  @Html.ValidationMesageFor(m => m.Name)

  @Html.LabelFor(m => m.TC)
  @Html.DropDownListFor(m => m.TC, Model.TCList, "Please select")
  @Html.ValidationMesageFor(m => m.TC)

  <input type="submit" ... />
}
  • 1
    Is it possible that i add `HiddenFor` in my View that I have? Where am i wrong?? Does it mean that if I have values of more than one class being accessed in a view i need to define ViewModel. but isnt't it explicit by creating the foreign key. i don't know if my way of thinking is right. – Vini Sep 25 '15 at 08:27
  • Yes, but there are numerous reasons why it could fail. Always use a view model. See also [What is ViewModel in MVC?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Sep 25 '15 at 08:30
  • But i tried hiddenfor in my code. But it doesnt work. Nor it throws any exception. Nothing happens when i click create. Nor my database is being updated. – Vini Sep 25 '15 at 08:32
  • According to my understanding, I my addingof HiddenFor should work. But I am unable to set the value of LsystemId in create. So there comes the use of ViewModel, Am i right? Or is there a way I canset the value of LsystemId in create in my case. – Vini Sep 25 '15 at 08:45
  • I want to be.. but i want to know why mine is not working.. If my way was right i should get it working.. I understand using viewmodel is the conventional way of getting things done now. Lets make it this way i want to figure it out for my curiosity. – Vini Sep 25 '15 at 08:52
  • See this [DotNetFiddle](https://dotnetfiddle.net/Omi8oi) for an example of what you should be doing –  Sep 25 '15 at 08:53
  • I can't comment on whats not working with your new code because I have not seen it :) –  Sep 25 '15 at 08:54
  • `@Html.HiddenFor(model=>model.LsystemID)` I have added this line to my view and no dropdownlist. My model reamins the same.. I am looking for an equivalent like :`Lsystem = id` in my create – Vini Sep 25 '15 at 08:59
  • Delete what? But i thought i should also learn my mistakes. so that i never do it again. – Vini Sep 25 '15 at 09:05
  • And did you miss the link to the fiddle? – Vini Sep 25 '15 at 09:06
  • Its the same link as before. And if you want to know what you are doing wrong with your current code, ask a new question with the relevant code (I can't guess what you have done) –  Sep 25 '15 at 09:08
  • I have edited my create and view like what i have now. I still have the same problem: my create button not workin, no exceptions – Vini Sep 25 '15 at 09:15
  • You CANNOT keep editing your question making everyones comments and answer irrelevant. Your problem is your have set `LsystemID = id` but then set `LsystemID` to a `SelectList` in the next line of code. Look at the html your generating (the value of the hidden input to understand why that value cannot then be bound to a property which is type of `int` when you post –  Sep 25 '15 at 09:18
  • The fiddel doesnt excute.. it exits with fatal error : Execution time limit exceeded – Vini Sep 25 '15 at 09:21
  • Sometimes happens when there is is a lot of use on the site (it was fine when I created it) –  Sep 25 '15 at 09:22
  • I thought i need to edit the question based on the progress. Even if my question was edited the things remain the same. Maybe i don't edit my code again.. – Vini Sep 25 '15 at 09:22
  • Add new code or revisions to code, don't change what you initially posted. –  Sep 25 '15 at 09:23
  • OK! My bad!! Now i forgot to comment the select list in what i posted. But i had it right on my code in the system. Still it doesn't work. and i could not understand your point about `HiddenFor` – Vini Sep 25 '15 at 09:25
  • OK. This comment is irrelevant in this scenario. Is it like after you submit the form it again comes back to the view? Because you have another div section after the submit.. It would be helpful for me in another scenario.. :) – Vini Sep 25 '15 at 09:28
  • Now i have solved my issue. I forgot to pass the model to the view.. i have got it right..# – Vini Sep 25 '15 at 09:29
  • So what does that mean? Your going to keep using your data model? –  Sep 25 '15 at 09:59
  • The comment in the fiddle is not irrelevant at all. It was to prove that it does bind correctly . –  Sep 25 '15 at 10:10
  • Not really.. But i just wanted to figure out why my code wasn't getting right.. I will surely change my code to your way. But i am sure I will come up with more questions because i haven't really got the full essence of your thinking in my scenario. – Vini Sep 25 '15 at 10:11
  • i was actually explaining my comment.. Not the comment about your fiddle. I was expecting a reply like _You should post another question to get an answer_ So i mentioned it explicitly that i am aware about the fact that my question in the comment is irrelevant – Vini Sep 25 '15 at 10:13
  • I have noticed you have numerous previous questions which seem to be related t this one. Are they the same? (in which case you should consider deleting them) or do some still need answering? –  Sep 25 '15 at 11:25
  • they need to be answered. And am i not supposed to post the questions with the same variables? – Vini Sep 25 '15 at 11:26
  • and the other questions are not the same. Each question has the same content but the answer i require is different. But i think i have sorted out most on my own but have left the question just to get a better advice or a diff way of doing – Vini Sep 25 '15 at 11:27
  • Yes of course you can :) They just looked very similar to this one (I only glanced at them). –  Sep 25 '15 at 11:28
  • They are all similar because everything has the Lsystem, Option, TC and etc. Because i have been working around this for quite a while. May be by next week i have another set of classes to work on :) – Vini Sep 25 '15 at 11:29
  • [http://programmers.stackexchange.com/questions/298138/designing-my-classes-with-relationships?noredirect=1#comment619083_298138]. I dont know if this can be done here. But i was wondering as you have got it right with my code, do you find anything odd with my data model? – Vini Sep 25 '15 at 11:31
  • No time now, But if I get a chance I will have a look over the weekend. But you really should consider naming your classes and properties so they make sense to others (code readability is important - `TC` should be TechnicalCharacterisic`) –  Sep 25 '15 at 11:37
  • I am just doing the trial version just to check if all the functionalities are working. But when i do the real thing i would make sure to give proper names.. And thanks a lot for such a huge help.. And thanks again for the consideration.. – Vini Sep 25 '15 at 11:42
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/90729/discussion-between-vini-vasundharan-and-stephen-muecke). – Vini Sep 27 '15 at 12:07