Monday 5 October 2020

Form post ASP.Net | C# | MVC

 


HTTP is a protocol that is used to provide a communication interface between server and client. HTTP sends data to the server and retrieved response to the client(Browser). HTTP has many methods for client/server communication.

HTTP GET and HTTP Post is the most common method used by HTTP. 

  • HTTP Get the return response from the server to  client.
  • HTTP Post send data client (Browser to the server) .
I am going to explain to you that how can you save data of a form using form post methods. I was a PHP developer when used the MVC C# form then I had to use ajax for data submission to the server which was very time taking and prone to error.


ASP.Net MVC C# has a built-in model attached view for form data submission and validation, which is good but not good as for users who are using simple posts form the method. So I will show you different ways to send data to the server using form method post like PHP.

Demo Table Name (Student)


SN

Field

Data Type

1

Roll

Int

2

Name

Varchar(50)

3

City

Varchar(50)

Store Procedure


create Proc[dbo].[AddStudent]
(
     @roll int,@name varchar(50),city varchar(50)
)
AS
BEGIN
     insert into student values(@roll,@name,@city)        
end

HTML Form

<form method="post">

Roll : <input type="text" name="Roll" required  /><br />

Name : <input type="text" name="Name" required  /><br />

City : <input type="text" name="City" required  /><br />

<input type="submit" name="submit" value="Save" />

</form>

Model

public class Student
{
        public string Roll { get; set; }

        public string Name { get; set; }

        public string City { get; set; }
 }

Method 1 (Model attached View)

I hate this method because it is complicated to make a form using razor

@model ProbuzzMediaWebsite.Models.UserModel

<script src="~/Scripts/jquery-1.10.2.min.js"></script>

<script src="~/Scripts/jquery.validate.min.js"></script>

<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

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

    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    @Html.LabelFor(model => model.Roll, new { @class = "control-label" })               

    @Html.EditorFor(model => model.Roll) <br />

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

       

    @Html.LabelFor(model => model.Name, new { @class = "control-label" })               

    @Html.EditorFor(model => model.Name) <br />

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

          

    @Html.LabelFor(model => model.City, new { @class = "control-label" })               

    @Html.EditorFor(model => model.City) <br />

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

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

}

Controller

[HttpPost]

   [ValidateAntiForgeryToken]

public ActionResult StuAdd(FormCollection data)
{

            string ErrMsg = "";

            UserModel ob = new UserModel();

            AdminRepository cob = new AdminRepository();

            Boolean flag = true;

            if (ModelState.IsValid)

            {

                ob.Roll = data["Roll"];

                ob.Name = data["Name"];

                ob.City = data["City"];

                flag = cob.SaveEmployee(ob, ref ErrMsg);

                if(ErrMsg=="")

                    return RedirectToAction("EmployeeIndex","CRMAdmin");

                else

                    return RedirectToAction("Error","Common", new { msg = @ErrMsg});

                   

            }

            return RedirectToAction("/Common/Error");

}

Method 2

[HttpPost]
public ActionResult StuAdd(StudentModel data)
{

            string ErrMsg = "";

            CommonRepository ob = new CommonRepository();

             if(ob.SavePostReport(data,ref ErrMsg))               

                return RedirectToAction("ClientPost","Operator");

            else

                return RedirectToAction("Error", "Common", new  {msg=ErrMsg });

}

Note :

This is the best method to pass data to form post because PHP uses the same approach. Make sure that your model member name and HTML form control name must be matched.


Repository

public bool SaveStudent(StudentModel ob, ref string ErrMsg)
{

            String result = "";

            try

            {

                using (SqlConnection dbcon = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ToString()))

                {

                    using (SqlCommand cmd = new SqlCommand("[dbo].[AddStudent]", dbcon))
                    {

                        cmd.CommandType = CommandType.StoredProcedure;

 

                        cmd.Parameters.AddWithValue("@roll", Convert.ToInt16(ob.Roll));

                        cmd.Parameters.AddWithValue("@name", ob.Name);

                        cmd.Parameters.AddWithValue("@city", ob.City);                      

                        if (dbcon.State == ConnectionState.Closed)

                            dbcon.Open();

                        cmd.ExecuteNonQuery();

                        result = "1";

                    }

                }

            }

            catch (Exception ex)

            {

                ErrMsg = ex.Message;

            }

            if (result == "1")

                return true;

            else

                return false;

}

Next Topic

No comments:

Post a Comment