简体   繁体   中英

c# mvc retrieve data from a view

I want to retrieve data from a view, it should work like this:

  1. User fill a form available on the webpage
  2. User clicks SEARCH button
  3. Some function(s) collect the data and display them in another view

I tried all the basic tutorials and tips on others stackoverflow question but it still doesn't work. I don't know what I'm doing wrong...

Here's my code from the view:

section id="roomSearch">
<div class="banner">
    <div class="banner-info">
        <div class="container">
            <div class="details-1">
                @using (Html.BeginForm("UploadRoomSearchData", "HomeController", FormMethod.Post, new { enctype = "multipart/form-data" }))
                {
                <div class="col-md-10 dropdown-buttons">

                    <div class="col-md-3 dropdown-button">

                            @Html.AntiForgeryToken()

                            <div class="input-group">
                                @Html.TextBoxFor(m => m.YourName, new { @class = "form-control has-dark-background", @placeholder = "Imię" })

                                @Html.ValidationMessageFor(m => m.YourName, "", new { @class = "text-danger" })
                                <!--<input class="form-control has-dark-background"
                name="slider-name" id="slider-name" placeholder="Imię" type="text" required="">-->
                            </div>


                    </div>
                    <!---strat-date-piker---->
                            <link rel="stylesheet" href="~/Content/jquery-ui.css" />
                            <script src="~/Scripts/jquery-ui.js"></script>
                            <script>
                                $(function () {
                                    $("#datepicker,#datepicker1").datepicker();
                                });
                            </script>
                    <!---/End-date-piker---->

                            <div class="col-md-3 dropdown-button">
                                <div class="book_date">
                                    <form>
                                        <input class="date" id="datepicker" type="text" value="Przyjazd" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Przyjazd';}">

                                       <!-- @Html.TextBoxFor(m => m.CheckIn, new { @class = "date" })
                                        @Html.ValidationMessageFor(m => m.CheckIn, "", new { @class = "datefield" })-->
                                            </form>
                                </div>
                            </div>
                            <div class="col-md-3 dropdown-button">
                                <div class="book_date">
                                    <form>
                                     <input class="date1" id="datepicker1" type="text" value="Wyjazd" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Wyjazd';}">

                                        <!--@Html.TextBoxFor(m => m.CheckOut, new { @class = "date1" })
                                        @Html.ValidationMessageFor(m => m.CheckOut, "", new { @class = "datefield" })-->
                                            </form>
                                </div>
                            </div>
                            <div class="col-md-3 dropdown-button">
                                <div class="section_1">
                                    <select id="country" onchange="change_country(this.value)" class="frm-field required">
                                        <option value="null">Dwuosobowy</option>
                                        <option value="null">Jednoosobowy</option>
                                        <option value="AX">Apartament</option>
                                        <option value="AX">Gościnny</option>
                                    </select>
                                </div>
                            </div>

                            <div class="clearfix"> </div>
                        </div>
                            <div class="col-md-2 submit_button">
                                <form  >

                                    <input type="submit"  value="SZUKAJ">
                                 <!-- <p> @Html.ActionLink("SZUKAJ", "Book1", "Home")</p>-->

                                </form>


                </div>}

And here's my code in the controller. For now I try to retrieve only a name, to see if it's working.

[HttpPost]
    public ActionResult UploadRoomSearchData(FormCollection form)
    {
        string name = Request["YourName"].ToString();

        StringBuilder sbRoom = new StringBuilder();

        sbRoom.Append("<b>Amount :</b> " + name + "<br/>");

        //return RedirectToAction("Book1");

        return Content(sbRoom.ToString());

    }

I also tried something like this:

foreach(var v in form)
{
    Write.Response("name:" + v);
 }

I tried your code and it seems to work. First I have the controller method to display the form

public ActionResult CreatePerson()
    {
        Person model = new Person();
        return View(model);
    }

Then the form:

@model RetrieveDataFromaView.Models.Person
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Person</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.YourName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.YourName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.YourName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="submit" class="btn btn-default" />
        </div>
    </div>
</div>
}

Which does a post to the controller method

[HttpPost]
    public ActionResult CreatePerson(FormCollection formCollection)
    {
        string name = Request["YourName"].ToString();
        StringBuilder sbRoom = new StringBuilder();
        sbRoom.Append("<b>Amount :</b> " + name + "<br/>");
        return Content(sbRoom.ToString());
    }

This returns a view with only the content of the StringBuilder. Maybe you are looking for RedirectToAction ?

Hello you have this line inside the form:

@Html.AntiForgeryToken()

You can remove it or add the corresponding attribute to use it:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreatePerson(FormCollection formCollection)
{
    ///Your code here
}

Basically this is a token generated for the server to avoid requests from forms not generated by the server.

You have many ways of retrieving data from a form Post in ASP.NET MVC.

Using a Model

Usually, forms are created by specifying a Model type in the Razor view. You can use that type to retrieve the data. ASP.NET MVC will parse the body and populate the object in parameter for you.

Ex:

Controller:

public class HomeController: Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        return View(new Person());
    }

    [HttpPost]
    public ActionResult Index(Person p)
    {
        //Just for the sake of this example.
        return Json(p);
    }
}

Razor view

@model WebApplication2.Models.Person

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>title</title>
</head>
<body>
    <div>
        @using (Html.BeginForm("Index", "Home", FormMethod.Post))
        {
            @Html.AntiForgeryToken()

            <div>
                @Html.LabelFor(m => m.FirstName): <br/>
                @Html.TextBoxFor(m => m.FirstName)
            </div>

            <div>
                @Html.LabelFor(m => m.LastName): <br/>
                @Html.TextBoxFor(m => m.LastName)
            </div>

            <input type="submit" value="Submit" />
        }
    </div>
</body>
</html>

Using a FormsCollection

The FormsCollection object allows you to access the raw values of a form. It acts as a Dictionary for the Forms value. This is useful, especially when you have a dynamic model to parse, or if you just plain don't know about the Model type.

It's also pretty straightforward to use.

[HttpPost]
public ActionResult Index(FormCollection form)
{
    var dict = form.AllKeys.ToDictionary(key => key, key => form[key]);

    return Json(dict);
}

PS: I saw you are using Request[key] . It may just be me, but this call just looks like Dark magic, where you get data from who knows where (it uses the Query String, the cookies, the Request body, etc. It seems like it could be really problematic in some cases in the future. I much prefer knowing exactly where the data comes from. But that may just be me.

Conclusion

In conclusion, use the Model approach if you know exactly what should be in the Form. Use the FormCollection approach if you really need to. That's pretty much it.

Good luck.

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