简体   繁体   English

C#MVC表单:如何利用html.editorfor的优势为简单的反馈表单构建视图?

[英]c# mvc form: how to build view for simple feedback form leveraging the benefit of using html.editorfor?

I have simple input form (basically for feedback) with following fields: Name, Gender, Mobile-Number, Complaint text. 我有一个简单的输入表单(主要用于反馈),其中包含以下字段:姓名,性别,手机号码,投诉文本。 (To simplify I am not mentioning any POST action OR submit button on the form) (为简化起见,我在表单上没有提及任何POST操作或提交按钮)

Currently, I have created following MVC structure: 目前,我已经创建了以下MVC结构:

public class ComplaintController
{
    [HttpGet]
    public ActionResult Index()
    {
       return View(); //This view displays the complaint form with all above fields
    }
}

I read this and several other links where they suggest to use @Html.EditorFor as it creates UI based on model data-type. 我阅读了此文章以及其他一些链接,他们建议使用@ Html.EditorFor,因为它基于模型数据类型创建UI。

Currently, I am not passing any model to the [HttpGet] view. 当前,我没有将任何模型传递给[HttpGet]视图。 If I want to use @Html.EditorFor, I need to pass my model to [HttpGet] Index View, how can I do that? 如果要使用@ Html.EditorFor,则需要将我的模型传递给[HttpGet]索引视图,该怎么办? What is best pratise to create such MVC forms? 创建此类MVC表单的最佳做法是什么?

Your Controller: 您的控制器:

    public ActionResult Index()
    {
        whateverModel d = new whateverModel();
        return View(d);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(whateverModel m)
    {

        if (ModelState.IsValid)
        {

           //its valid, update your database or do soemthing useful here
           return RedirectToAction("Success");
        }
        //its not valid reload the page and let data annotations show the error
        return View(m);
    }

Once you have your code in the controller then you can have visual studio auto-create your view. 将代码放入控制器后,即可让Visual Studio自动创建视图。 In your controller, right click the "d" in return View(d); 在您的控制器中,右键单击“ d”以返回View(d); and select "Add View." 并选择“添加视图”。 Change the Template to "create" and Model class to your Model (whateverModel in this example). 将模板更改为“ create”,并将Model类更改为您的Model(在此示例中为whatModel)。 It will auto generate the chtml page for you with the model imported and the editors already generated for you. 它将自动为您生成chtml页面,其中包含导入的模型以及已经为您生成的编辑器。 Example auto generated view below. 以下示例自动生成的视图。 The you can work on styling and such. 您可以从事样式等工作。

cshtml: cshtml:

    @model YourSolution.Models.whateverModel

    @{
        ViewBag.Title = "Whatever";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }

    <h2>Whatever</h2>

    @using (Html.BeginForm()) 
    {
        @Html.AntiForgeryToken()

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

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

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

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>

Currently, I am not passing any model to the [HttpGet] view. 当前,我没有将任何模型传递给[HttpGet]视图。 If I want to use @Html.EditorFor, I need to pass my model to [HttpGet] Index View, how can I do that? 如果要使用@ Html.EditorFor,则需要将我的模型传递给[HttpGet]索引视图,该怎么办?

Hi sahil ,As a first step , create one model class like below 嗨,希尔,第一步,创建一个如下的模型类

public class FeedBack
{
   public string  Name{get;set;}
   public string  Gender{get;set;}
   public int  Mobile-Number{get;set;}
   public string  Complaint{get;set;}

  // other additional fields


}

And in the controller get method ,pass a model like below 并在控制器的get方法中,传递如下模型

public class ComplaintController
{
    [HttpGet]
    public ActionResult Index()
    {
      FeedBack OBJFeedback = new FeedBack();    
       return View(OBJFeedback); 
    }
}

And in a view , strongly type this model and post the data as you want to the controller post methods. 在视图中,强烈键入此模型并将所需的数据发布到控制器的post方法。

Here is the example of strongly typed view : http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/strongly-typed-views-in-mvc/ 这是强类型视图的示例: http : //www.c-sharpcorner.com/UploadFile/abhikumarvatsa/strongly-typed-views-in-mvc/

Important Note : In the get action method , since you dont want to display any values by default in the view , even if you dont pass model object it will work in the same way. 重要说明:在get action方法中,由于您不想在视图中默认显示任何值,即使您不传递模型对象,它也将以相同的方式工作。

Hope the above information was useful 希望以上信息对您有所帮助

Thanks 谢谢

Karthik 卡尔提克

If you want to use @Html.EditorFor, then you mast pass the model to the view.What does @Html.EditorFor do? 如果要使用@ Html.EditorFor,则可以将模型传递给视图。@ Html.EditorFor有什么作用? It makes the html tag like 它使html标签像

<input class="text-box single-line" id="Name" name="Name" type="text" value="">

So if you do not want to pass the model to the view then you need to write the raw html tag like above. 因此,如果您不想将模型传递给视图,则需要像上面那样编写原始的html标签。 It is important to keep the html tag's name property same as the mvc's model property because when you want to post the data to the controller the name property of the html tag will map the mvc model property and get the corresponding value at the Controller method. 保持html标签的name属性与mvc的model属性相同很重要,因为当您要将数据发布到控制器时,html标签的name属性将映射mvc model属性并在Controller方法中获取相应的值。

At the view(somthing.cshtml) you can use html tags, because .cshtml==.cs+html . 在视图(somthing.cshtml)上,您可以使用html标签,因为.cshtml ==。cs + html。 So the whole code look like 所以整个代码看起来像

Controller methods 控制器方法

 public ActionResult FeedBack()
 {
     return View();
 }



[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult FeedBack(FeedBackModel Model)
{
    var feedBack = Model;
     return View();
 }

And the View 和看法

<form action="/Home/FeedBack" method="post" id="feedBackForm">
    @Html.AntiForgeryToken()
    <hr>
    <div class="form-group">
        <div class="col-md-5">
            <label for="Name">Name</label>
        </div>
        <div class="col-md-5">
            <input class="text-box single-line" name="Name" type="text">
        </div>
        </div>
    <div class="form-group">
        <div class="col-md-5">
            <label for="Name">Gender</label>
        </div>
        <div class="col-md-5">
            <select name="Gender">
                <option value="male">Male</option>
                <option value="female">Female</option>
            </select>
        </div>
        </div>
    <div class="form-group">
        <div class="col-md-5">
            <label for="Name">MobileNumber</label>
        </div>
        <div class="col-md-5">
            <input class="text-box single-line" name="MobileNumber" type="text">
        </div>
        </div>
    <div class="form-group">
        <div class="col-md-5">
            <label for="Name">Complaint</label>
        </div>
        <div class="col-md-5">
            <textarea class="text-box single-line" name="Complaint"></textarea>
        </div>
        </div>


    <div class="col-md-5">
        <input type="submit" value="Create" class="btn btn-default">
    </div>
</form>

If you do not want to use submit then you can use ajax. 如果您不想使用submit,则可以使用ajax。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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