Resolved Can we render same view from different action methods?

Anonymous

Well-known member
Joined
Sep 29, 2020
Messages
84
Programming Experience
Beginner
Hello,

I am creating a test website for practice. The homepage looks like this -

1660742643961.png


On clicking test The view is

1660743468295.png


I want that when I click ID, a message should be displayed underneath the text box telling if the id is valid or invalid. Im using MVC architecture and connecting to database using ado.net.

I am able to get my invalid/valid message correctly but on getting exception in the return view code below saying cant find the view TestSite.

C#:
 public IActionResult TestSite(Test obj)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    DataAccess site = new DataAccess();

                    if (site.checkSite(obj))
                    {
                        ViewBag.Message = "Site Id is valid";
                    }
                    else
                        ViewBag.Message = "Site Id is invalid";
                }

                return View();
                
            }
            catch
            {
                return View();
            }
        }

How can I return the same view as above with the message?

This is my cshtml page

C#:
@model PracticeWebsite.Models.Test
<h1>Test</h1>
@using (Html.BeginForm("TestSite", "Home", FormMethod.Post))
{
    @Html.TextBoxFor(model => model.sID)
    @Html.ValidationMessageFor(model => model.sID)
    <button type="submit">Enter ID</button>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10" style="color:green">
            @ViewBag.Message

        </div>
        </div>
        }
 

Attachments

  • 1660742678155.png
    1660742678155.png
    2.9 KB · Views: 11
Recall, that Microsoft's MVC was created in response to Ruby on Rails to prevent people from jumping ship from ASP.NET and the inferior WebForms of writing web code to the RoR. As part of that response (as well as taking in the accepted "of course that's that way to do things"), MVC not only uses RoR's usage of the MVC pattern, but it also uses the RoR "coding by convention" practice. So with MVC, the convention is that if the controller action is called ShootMeInTheFoot, then there needs to be a view called ShootMeInTheFoot as well. Why? Because that's the convention.

Fortunately, you can tell MVC to use another view instead:
 
Back
Top Bottom