Monday, May 8, 2023

MVC Html.BeginForm Complete Example

 In this chapter, you will learn:

  1. What is Html.BeginForm?
  2. How to Create Html.BeginForm
  3. How to Pass Form Data to Controller
  4. Complete Programming Example

WHAT IS HTML.BEGINFORM?

Html.BeginForm is the Html Helper Extension Method that is used for creating and rendering the form in HTML. This method makes your job easier in creating form. Here, is the method to create a form using Html.BeginForm extension method in ASP.NET MVC5.


Html.BeginForm("ActionMethod", "ControllerName","Get⁄Post Method")

Generally, 3 parameters are used when creating Html.BeginForm
ActionMethod – It defines which action method is look for when submit button is clicked.
ControllerName
 – It defines, which controller keeps the defined action method.
Get/Post Method – it defines the method you want to use to send data from form to controller.

PROGRAMMING EXAMPLE:


Model: UserModel.cs

  1. namespace HtmlHelperDemo.Models
  2. {
  3. public class UserModel
  4. {
  5. public string UserName { get; set; }
  6. public int Age { get; set; }
  7. public string City { get; set; }
  8. }
  9. }

View: Index.cshtml

  1. @using HtmlHelperDemo.Models
  2. @model UserModel
  3.  
  4. <h1>Html.DisplayFor Example</h1>
  5.  
  6. @using (Html.BeginForm("Index", "Home", FormMethod.Post))
  7. {
  8. <span>Enter Your Name:</span> @Html.TextBoxFor(m => m.UserName)<br />
  9. <span>Enter Your Age: </span> @Html.TextBoxFor(m => m.Age)<br />
  10. <span>Enter Your City: </span>@Html.TextBoxFor(m => m.City)<br />
  11.  
  12. <input id = "Submit" type = "submit" value = "submit" />
  13. }
  14.  
  15. <hr />
  16.  
  17. <strong>User Name: </strong> @Html.DisplayFor(m => m.UserName)<br />
  18. <strong>User Age: </strong> @Html.DisplayFor(m => m.Age)<br />
  19. <strong>User City: </strong> @Html.DisplayFor(m => m.City)<br />

Controller: HomeController.cs

  1. namespace HtmlHelperDemo.Controllers
  2. {
  3. public class HomeController : Controller
  4. {
  5. public ActionResult Index()
  6. {
  7. return View();
  8. }
  9.  
  10. [HttpPost]
  11. public ActionResult Index(UserModel um)
  12. {
  13. return View(um);
  14. }
  15. }
  16. }

OUTPUT

Html.BeginForm Example

SUMMARY:

However, there is a lot thing to learn in WebForms but this chapter focuses on simple understanding on how Html.BeginForm can be created. I added the simple but complete programming example that will surely help you to create a form using Html.BeginForm Extension Method. However, I have also written some advanced topic on WebForms and if you want to learn more about this, please visit the following article.


https://www.completecsharptutorial.com/asp-net-mvc5/html-beginform-example-tutorial-aspnet-mvc5.php

Sunday, May 7, 2023

Razor syntax demo

 <h1>Razor syntax demo</h1>

<p>Demo 1</p>

<h2>@DateTime.Now.ToShortDateString()</h2>


<p>Demo 2</p>

@{

    var date = DateTime.Now.ToShortDateString();

    var message = "Hello World";

}


<h2>Today's date is: @date </h2>

<h3>@message</h3>


<p>Demo 3</p>


@{

    var date1 = DateTime.Now.ToShortDateString();

    string message1 = "Hello World!";

    @:Today's date is: @date1

    <br />

    @message1

}


<p>Demo 4</p>


@{

    var date2 = DateTime.Now.ToShortDateString();

    string message2 = "Hello World!";

    <text>Today's date is:</text> @date2

    <br />

    @message2

}


<p>Demo5if-else condition:</p>

@if (DateTime.IsLeapYear(DateTime.Now.Year))

{

    @DateTime.Now.Year @:is a leap year.

}

else

{

    @DateTime.Now.Year @:is not a leap year.

}


<p>Demo 6</p>

for loop:


@for (int i = 0; i < 5; i++)

{

    @i.ToString()

    <br />

}

<p>Demo 7</p>

Declare Variables


@{

    string str = "";


    if (1 > 0)

    {

        str = "Hello World!";

    }

}


<p>@str</p>


<p>Demo 8</p>

Model


@model MVCDemo.Models.PersonalDetail


@Model.FirstName 

Unit-4 Lab



 

 

 

Models/Student.cs

 

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Web;

 

namespace MVCDemo.Models

{

    public class Student

    {

        public int StudentId { get; set; }

 

        [Display(Name = "Name")]

        public string StudentName { get; set; }

 

        public int Age { get; set; }

    }

 

    public class Standard

    {

        public int StandardId { get; set; }

        public string StandardName { get; set; }

    }

}

 

Controllers / StudentController.cs

 

using MVCDemo.Models;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace MVCDemo.Controllers

 

{

    public class StudentController : Controller

    {

        static IList<Student> studentList = new List<Student>{

                new Student() { StudentId = 1, StudentName = "John", Age = 18 } ,

                new Student() { StudentId = 2, StudentName = "Steve",  Age = 21 } ,

                new Student() { StudentId = 3, StudentName = "Bill",  Age = 25 } ,

                new Student() { StudentId = 4, StudentName = "Ram" , Age = 20 } ,

                new Student() { StudentId = 5, StudentName = "Ron" , Age = 31 } ,

                new Student() { StudentId = 4, StudentName = "Chris" , Age = 17 } ,

                new Student() { StudentId = 4, StudentName = "Rob" , Age = 19 }

            };

 

        // GET: Student

        public ActionResult Index()

        {

            //fetch students from the DB

 

            return View(studentList.OrderBy(s => s.StudentId).ToList());

        }

        public ActionResult Edit(int id)

        {

            //Get the student from studentList sample collection for demo purpose.

            //You can get the student from the database in the real application

            var std = studentList.Where(s => s.StudentId == id).FirstOrDefault();

 

            return View(std);

        }

 

        [HttpPost]

        public ActionResult Edit(Student std)

        {

            //write code to update student

            //update student in DB in real-life application

 

            //update list by removing old student and adding updated student for demo

            var student = studentList.Where(s => s.StudentId == std.StudentId).FirstOrDefault();

            studentList.Remove(student);

            studentList.Add(std);

            return RedirectToAction("Index");

        }

 

    }

 

 

}

 

 

Index.cshtml

@model IEnumerable<MVCDemo.Models.Student>

 

@{

    ViewBag.Title = "Index";

    Layout = "~/Views/Shared/_Layout.cshtml";

}

 

<h2>Index</h2>

 

<p>

    @Html.ActionLink("Create New", "Create")

</p>

<table class="table">

    <tr>

        <th>

            @Html.DisplayNameFor(model => model.StudentName)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.Age)

        </th>

        <th></th>

    </tr>

 

    @foreach (var item in Model)

    {

        <tr>

            <td>

                @Html.DisplayFor(modelItem => item.StudentName)

            </td>

            <td>

                @Html.DisplayFor(modelItem => item.Age)

            </td>

            <td>

                @Html.ActionLink("Edit", "Edit", new { id = item.StudentId }) |

                @Html.ActionLink("Details", "Details", new { id = item.StudentId }) |

                @Html.ActionLink("Delete", "Delete", new { id = item.StudentId })

            </td>

        </tr>

    }

 

</table>

 

Edit.cshtml

@model MVCDemo.Models.Student

 

@{

    ViewBag.Title = "Edit";

    Layout = "~/Views/Shared/_Layout.cshtml";

}

 

<h2>Edit</h2>

 

@using (Html.BeginForm())

{

    @Html.AntiForgeryToken()

 

    <div class="form-horizontal">

        <h4>Student</h4>

        <hr />

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.HiddenFor(model => model.StudentId)

 

        <div class="form-group">

            @Html.LabelFor(model => model.StudentName, htmlAttributes: new { @class = "control-label col-md-2" })

            <div class="col-md-10">

                @Html.EditorFor(model => model.StudentName, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.StudentName, "", new { @class = "text-danger" })

            </div>

        </div>

 

        <div class="form-group">

            @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })

            <div class="col-md-10">

                @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })

                @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })

            </div>

        </div>

 

        <div class="form-group">

            <div class="col-md-offset-2 col-md-10">

                <input type="submit" value="Save" class="btn btn-default" />

            </div>

        </div>

    </div>

}

 

<div>

    @Html.ActionLink("Back to List", "Index")

</div>

 

 

https://www.tutorialsteacher.com/mvc/create-edit-view-in-asp.net-mvc

https://www.codingninjas.com/codestudio/library/asp-net-create-edit-view

http://www.dotnettpoint.com/MVC/CreateEditView

https://stackoverflow.com/questions/42202510/need-to-display-the-required-field-of-the-student-table

 

Lab 3 Unit -5 Database

   private void button1_Click(object sender, EventArgs e)         {             ProductDbEntities productDb = new ProductDbEntities();      ...