Save data to .net mvc

I am implementing a search module with search engine support for the results page. The example provided by NerdDinner passes pagenumber as a parameter to the index action, and the action uses pagenumber to execute the query each time the user clicks a different page number.

My problem is that my search has much more criteria, such as price, material, model number, etc., and not just a simple pagenumber. Therefore, I would like to save the criteria after the first user submission, so I only need to pass pagenumber back and forth.

Using ViewData is not possible because ViewData is cleared after it is sent to the view.

Is there a good way to save the criteria data as I would like?

+2
source share
1 answer

You have two ways to do this.

  • Put the data that you want to keep in a serializable session, cache or database. Putting it in the database will be the safest choice, but it will degrade your performance.

  • You can save the saved data in a hidden html tag. As long as the information is not sensitive, this option should work well.

here is some supporting code. You can use this in only one controller

public class questionController : Controller
{
    public QuestionFormData qdata;

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        qdata = (SerializationUtil.Deserialize(Request.Form["qdata"])
            ?? TempData["qdata"]
            ?? new QuestionFormData()) as QuestionFormData;
        TryUpdateModel(qdata);
    }

    protected override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        if (filterContext.Result is RedirectToRouteResult)
        {
            TempData["qdata"] = qdata;
        }
    }

Access to updated information like this.

    public ActionResult Index()
    {
         DateTime d = qdata.date;
    }

On aspx page

<%= Html.Hidden("qdata", SerializationUtil.Serialize(Model)) %>
+2
source

Source: https://habr.com/ru/post/1717787/


All Articles