Is it reasonable to simulate ispostback in asp.net core mvc?

Xie Steven 831 Reputation points
2021-09-18T01:24:25.707+00:00

I'm porting my old ASP.NET Webform project to ASP.NET Core MVC. Due to various reasons, I need to keep the original code as much as possible to save manpower and material resources.

Then, in oruginal code, there's a IsPostBack property on every page. When the page is initializing, it will call a 'InitPage()' method. If the request is postback, it will not call the 'InitPage()' method again, it will call 'DoSomething()' method instead.

But now, I face such a issue. When the view is rendered at first time, this method worked well. We assume that all 'Index.cshtml' views are the initial views of all controllers.

For example, we have a 'HomeController', and there're 'Index' and 'Search' actions in it. They all accept 'GET' request.

When we access the 'http://localhost:xxx/Home/Index', the 'IsPostBack()' worked as we expected. When we access 'Search', the 'IsPostBack()' didn't work. It still call 'InitPage()' method for every request. I can understand this behavior, it's due to the url is changed and it's 'GET' request. But even if we make the 'Search' action accept 'POST' request. It still call 'InitPage()' method at first request.

So, my main target is hold the fixed properties value in ViewModel after 'InitPage()' method is called. Then, I do not need to call 'InitPage()' method every time in other action methods of the same controller.

Please give me some suggestions and make me on the right direction.

The following is the code:

public class HomeController : BasePage
{
    private HomeViewModel viewModel;
    public HomeController()
    {
        viewModel = new HomeViewModel();
    }

    public override void PageLoaded()
    {
        if (!IsPostBack())
        {
            this.InitPage();
        }
        else
        {
            // Do something.
            this.viewModel.LabelName = this.HttpContext.Session.Get("Name").ToString();
        }
    }

    public IActionResult Index()
    {
        return View(this.viewModel);
    }

    public IActionResult Search()
    {
        Random rn = new Random();
        this.viewModel.Content = "rn : " + rn.Next(100);
        return View("Index", this.viewModel);
    }

    private void InitPage()
    {
        this.viewModel.LabelName = "Steven -- " + DateTime.Now.ToString();
        this.HttpContext.Session.Set("Name", Encoding.Default.GetBytes("this.viewModel.LabelName "));
    }
}

public class BasePage : Controller
{
    public virtual void PageLoaded() { }

    public override void OnActionExecuting(ActionExecutingContext context)
    {
        this.PageLoaded();
        base.OnActionExecuting(context);
    }

    protected bool IsPostBack()
    {
        var request = HttpContext.Request;
        var currentUrl = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path, request.QueryString);
        var referrer = request.Headers["Referer"].FirstOrDefault();

        bool isPost = string.Compare(request.Method, "POST",
        StringComparison.CurrentCultureIgnoreCase) == 0;
        if (referrer == null) return false;

        bool isSameUrl = string.Compare(currentUrl,
        referrer,
        StringComparison.CurrentCultureIgnoreCase) == 0;

        return isPost && isSameUrl;
    }
}

public class HomeViewModel
{
    public string LabelName { get; set; }

    public string Content { get; set; }
}

@{
    ViewData["Title"] = "Home Page";
}

@model WebApplication7.Controllers.HomeViewModel

<div class="text-center">
<form asp-action="Search" method="get">
    <label>@Model.LabelName</label><br/>
    <label>@Model.Content</label><br/>
    <input type="submit" value="Search"/>
</form>
</div>
Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 30,126 Reputation points
    2021-09-18T11:36:14.967+00:00

    Is it reasonable to simulate ispostback in asp.net core mvc?

    A PostBack in ASP.NET Web Forms is an HTTP Post. IsPostBack is a standard pattern in Web Forms to determine if the page request is a GET or a POST. This pattern does not apply to MVC.

    In MVC, the initialization code goes in an [HttpGet] action and the form processing code goes in an [HttpPost] action. There's no reason to check for post because the routing selects the [HttpGet] or [HttpPost] action.

    Reference docs

    Routing in ASP.NET Core


1 additional answer

Sort by: Most helpful
  1. Bruce Barker 801 Reputation points
    2021-09-18T15:19:25.99+00:00

    In webforms ispostback checked the method also. You were probably using link buttons (submit buttons styles as links with a command arg), rather than actual anchors, or you would have had the same behavior. You probably used server transfer.

    You can duplicate this in MVC, a server transfer is just return the call to the desired action. If it’s a different controller, you must create an instance first.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.