Darf Zon
Darf Zon

Reputation: 6378

In a post method, how to get compact parameters instead of all the object properties

Maybe the title is not so explicitly. Let me explain you my situation

I've got a get and post method in my controller. In the GET method, gets the entities from the database context

    [HttpGet]
    public ActionResult RecheckAssignment(short id)
    {
        var assignment = db.Assignments.Find(id);
        Session["QuestionList"] = QuestionRepositoryManager.GetAllPossibleQuestionsFromJson(assignment.Content);  // it's a list!

        return View(Session["QuestionList"]);
    }

Assignment entity contains as 10 properties. When I show this entities in the model, it shows uses all the properties, but when the user does post should get only two properties from it (Id string, Changed bool) in the POST METHOD.

I do not what to put inside of the method parameters.

    [HttpPost]
    public ActionResult RecheckAssignment(...)
    {
        return View();
    }

I put everything in a session variable because later I must have to get the entities again, I guess this is a good option using Session but I'm not sure.

So, what should I have to write inside of the method to get only the Id and Changed properties to updated the entities.

Upvotes: 1

Views: 181

Answers (1)

Mike Perrenoud
Mike Perrenoud

Reputation: 67918

When ASP.NET MVC maps a <form> back to the Action during a POST it will fill in what it can. Consider a class like this:

public class Car
{
    public string Make { get; set; }
    public string Model { get; set; }
    public int Year { get; set; }
}

and now consider this form:

@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post))
{
    Html.TextBoxFor(m => m.Make)
}

and now consider this Action:

public ActionResult ActionName(Car model)
{
    // the values of Car will look like this
    model.Make   // this will be what was in the text box
    model.Model  // this will be null
    model.Year   // this will be 0
}

and take note that null and 0 are the default values for those types. So, if I wanted to POST the property Model I need to get it in the form. I can do that with @Html.TextBoxFor, but what if I don't want the user to see it? Well, I can do that too:

Html.HiddenFor(m => m.Model);

and so now when the form is POSTed it will populate the Model with the value it was downloaded with. So, just make sure that all the properties you need are in the form in some way.

Upvotes: 1

Related Questions