简体   繁体   中英

Utilizing the same view for edit and view in ASP.net MVC

I have a controller action as follows

public ActionResult OpenForm()
{
    return View("Index");
}

And my View is as follows [Index.cshtml]

@model BusinessProcess.Models.HelloworldTO
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    @Html.DisplayNameFor(model => model.Response_Borrower)
    @Html.EditorFor(model => model.Response_Borrower)
}

Now the problem is I am using the same view for both "Edit" and "View". Now under certain circumstances I want the user to only "View" the data and convert the @Html.EditorFor to be @Html.DisplayFor . Is there any way to do it without creating another view?

Model:

public class HelloworldTO()
{
   public bool Edit {get; set;}
}

View:

@model BusinessProcess.Models.HelloworldTO
@if (Model.Edit)
{
   @using (Html.BeginForm())
   {
      @Html.ValidationSummary(true)

      @Html.DisplayNameFor(model => model.Response_Borrower)
      @Html.EditorFor(model => model.Response_Borrower)

   }
}
else
{
    @Html.DisplayFor(model => model.Response_Borrower)
 }

Controller

public ActionResult OpenForm()
{
    HelloworldTO model = new HelloworldTO ();
    model.Edit = /*certain circumstances*/;
    return View("Index", model);
}

Model

  public class Model1
{
    public bool SameView { get; set; }

    public bool Response_Borrower { get; set; }


}

View

@model CodeProjectAnswers.Models.Model1

@if (Model.SameView) {

// Do what you want 

} else { // code for the display

}

and in the controller some like below

  public ActionResult Sample()
    {

        Model1 model = new Model1();

        if (model.SameView)
        {
            // Set it to false and what is ur condition 
        }
        else
        {
            model.SameView = true;
        }

        return View("Sample", model);


    }

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