Egor Osaulenko
Egor Osaulenko

Reputation: 149

How could I pass a non default constructor object to Controller?

Sorry if this is an obvious question, but I didn't had much luck so far. I am having an input of a submit type in my View:

<input type="submit" 
       value="Remove Question" 
       class="btn btn-outline-danger" 
       [email protected]("Survey_RemoveQuestion", 
                              new Survey_Question_Wrapper() { 
                                  Survey = Model, 
                                  Question = Model.Questions[i] })/>

In my controller I have a handler, which looks like this:

  public ActionResult Survey_RemoveQuestion(Survey_Question_Wrapper s)
  {
      s.Survey.Questions.Remove(s.Question);
      return View("SurveyEdit", s.Survey);
  }

The Survey_Question_Wrapper has 2 constructors: a default empty one and the one, who accepts 2 parameters and assigns them to fields.

The problem which I am struggle with, is that the Survey_RemoveQuestion method is invoked with an object, build with the default constructor, so his fields are null's.

I believe there is something obvious I am missing. Many thanks in advance.

Upvotes: 1

Views: 106

Answers (1)

Emre Kabaoglu
Emre Kabaoglu

Reputation: 13146

No, the problem is not relevant with Survey_Question_Wrapper constructors. You are trying to pass the complex types to controller via GET. You can't send the complex types directly like that.

You should serialize it and send it as string. (I used Json.Net, you can use another library)

    <input type = "submit"
    value="Remove Question" 
    class="btn btn-outline-danger" 
    [email protected]("Survey_RemoveQuestion", 
    new
    {
        s = JsonConvert.SerializeObject(new Survey_Question_Wrapper
            {
                Survey = Model,
                Question = Model.Questions[i]
            }
        )
    })/>

And controller part looks like;

  public ActionResult Survey_RemoveQuestion(string s)
  {
      //Deserialize it
      var obj = JsonConvert.DeserializeObject<Survey_Question_Wrapper>(s);
      obj.Survey.Questions.Remove(obj.Question);
      return View("SurveyEdit", obj.Survey);
  }

Also, if you want to send complex types to server, its proper way to perform it using POST instead of GET.

Upvotes: 2

Related Questions