0

I am trying to pass a parameter to controller (or set a model property), check it, do action, reset the parameter, and return view. I have tried to create a property in my View Model and I set it in the view, I get the right value after posting it (GET) method but resetting doesn't seem to work. My View Model:

public class GridViewModel 
{
    ...other properties...
    public string exportBtn { get; set; }
}

My controller action:

//GET
public ActionResult Index(GridViewModel model)
{
    if (model.exportBtn == "true")
    {
        //do stuff
    }        
    ModelState.Clear(); 
    ModelState.Remove("exportBtn"); 
    model.exportBtn = "";
    return View(model);
}

And in the View I have:

$('#someButtonOnClick').on('click', function () {
    $('input[name=exportBtn]').val("true");
}

@Html.HiddenFor(modelItem=> Model.exportBtn)

There are other buttons that would call the same controller action for different purpose and I need to reset this value not to confuse it with other requests. Is there any other better way to pass a temporary value from View to Controller? I also tried, after looking some other posts, to pass new ViewModel

var newVM = new GridModel {exportBtn="" };
ModelState.Clear();
return View(mv);
return View(model); //either doesn't work
5
  • First you should not be passing a complex object to a GET method. Apart from the ugly query string, you could exceed the query string limit and throw and exception, and if the model contains properties which are complex objects or collections, binding will fail anyway.
    – user3559349
    Mar 19, 2015 at 23:36
  • ModelState.Clear(); removes model state, it does not reset the value of the model property. Your also need model.exportBtn = "someNewValue"; but the correct approach is to follow the PRG pattern.
    – user3559349
    Mar 19, 2015 at 23:39
  • Thanks for the comments @Stephen Muecke, I was looking for a bandaid solution since this was existing piece of code and a large method; but the best would be to follow PRG pattern. Forgot to add code where I set new value to the property (still doesnt work)
    – AidaM
    Mar 19, 2015 at 23:44
  • The use of @Html.HiddenFor(modelItem=> Model.exportBtn) suggests you are using a loop to generate controls - is that correct?
    – user3559349
    Mar 20, 2015 at 0:09
  • exportBtn control appears only once on the page and is not inside a loop. @StephenMuecke. Also I have managed to split the controller method into GET and POST but the issue still stays.
    – AidaM
    Mar 20, 2015 at 16:51

0

Your Answer

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

Browse other questions tagged or ask your own question.