Click here to Skip to main content
15,888,241 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
My application has a dashboard where it displays list of added records in a table, and has a button to add new records on same dashboard.

Now from list of records on dashboard if user opens any one of the record it should display that record in Read Only format, I already have a view to insert records I want to use same view for both operations.

any possibility to use same view for insert and display?

What I have tried:

I created two Mvc Action methods one for Insert and another for display and redirecting user to same view on both operations.

Insert:

[HttpGet]
       public ActionResult InsertRecord()
       {
           var model = new InsertViewModel();

           return View("InsertRecord",model);
       }


Display:
<pre> [HttpGet]
        public ActionResult DisplayRecord(int Id)
        {
           var model = new InsertViewModel();
           model=GetExistingRecords(Id);
           return View("InsertRecord",model);

        }


Here I want to DisplayRecord as readonly format on Display Action execution
Posted
Updated 12-Jan-21 22:00pm

1 solution

Well, you could, if you wanted a messy solution:
C#
public class InsertViewModel
{
    ...
    public bool ReadOnly { get; set; }
}
C#
[HttpGet]
public ActionResult InsertRecord()
{
    var model = new InsertViewModel { ReadOnly = false };
    return View(model);
}

[HttpGet]
public ActionResult DisplayRecord(int id)
{
    var model = GetExistingRecord(id);
    model.ReadOnly = true;
    return View(nameof(InsertRecord), model);
}
Razor
@model InsertViewModel
@{
    ViewBag.Title = Model.ReadOnly ? "Record Details" : "Insert Record";
}

@using (Model.ReadOnly ? null : Html.BeginForm())
{
    @if (!Model.ReadOnly)
    {
        @Html.HiddenFor(m => m.ReadOnly)
        @Html.AntiForgeryToken()
        @Html.ValidationSummary()
    }
    
    ...
    
    @if (Model.ReadOnly)
    {
        @Html.DisplayFor(m => m.SomeField)
    }
    else
    {
        @Html.EditorFor(m => m.SomeField)
    }
    
    ...
    
    @if (!Model.ReadOnly)
    {
        <input type="submit" />
    }
}
However, it would be much cleaner to use separate views for inserting and displaying the records.
 
Share this answer
 
Comments
Divyay208 13-Jan-21 11:20am    
Thanks for the reply.. I will create new view any how here also we are creating controls for display and Editor separately.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900