简体   繁体   中英

PageData fails to pass data in WebMatrix

I am building a website with WebMatrix. I would like users to enter their name in the main page and after redirection their name will be shown in the results of another form. But my code is not working.

This is a snippet of the main page:

@{
    if (IsPost) {
        PageData["fullname"] = String.Format("{0} {1}", Request.Form["mainForename"], Request.Form["mainSurname"]);
        PageData["redir"] = Request.Form["goTo"];
    }
}

<form name="mainForm" id="mainForm" method="post" action="foo.cshtml" onsubmit="return mainValid(this);">
    <h2>Please enter your name:</h2>
    <label for="mainForename" class="label">Forename:</label>
    <input type="text" name="mainForename" id="mainForename">
    <label for="mainSurname" class="label">Surname:</label>
    <input type="text" name="mainSurname" id="mainSurname">
    <input type="submit" name="goTo" value="Go to Form 1">
    <input type="submit" name="goTo" value="Go to Form 2">
</form>

This is a snippet of the page that the main page directs to:

@{
    if (IsPost) {
        var display = PageData["fullname"];
    }
}

<form name="form1" id="form1" method="post" onsubmit="return Valid(this);">
    <!-- some HTML code -->
    <input type="submit" name="submit" value="Get results">
    <p>@Html.Raw(display)</p>
</form>

But whatever value I have submitted in the mainForm , PageData["fullname"] and PageData["redir"] seem to have no values. What is the problem?

Any help would be appreciated.

I think PageData is only useful when combining subpages into a single page.

Instead, try the Session object where you are using PageData. Session will be available for all that user's pages.

So where you have PageData["fullname"] use Session["fullname"]

For more details, see http://www.mikesdotnetting.com/article/192/transferring-data-between-asp-net-web-pages

I find something that's not quite good in your code:

  1. Why your form action is set to a cshtml file? It has to be an action in a controler;
  2. Why are you using "hardcoded" form tag? Use @using(@Html.BeginForm('name', 'action', 'controller'...)
  3. Why do you need WebMatrix? 1st - its pretty old, 2nd it for grids - you have a form.

Use a model, and use @Html.TextBoxFor(x=>x.UserName) inside the @Html.BeginForm. Then post the form in the action you are posting to redirect to another page that contains the 2nd Form, and have a model. The post action should look somehow like this

[HttpPost]
public ActionResult RedirectToAnotherForm(MyModel model)
{
return View('SecondFormView', new SecondFormModel{
userName = model.name
})
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM