How to insert data into database using asp,net mvc and stored procedure

时间:2017-11-08 21:59:16

标签: c# asp.net sql-server asp.net-mvc stored-procedures

I'm using stored procedure to insert data into a table database; however whenever I do a button, the data is not sent to the database. In addition; I would like to give an error if nothing was entered in the database or success message saying that it was entered. Not sure how to insert data into the database; what did I leave out

Form

<h2>Requisition Screen</h2>


{
    @Html.AntiForgeryToken()
<div class="form-horizontal">
    <h4>Request Item</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <div class="form-group">
        @Html.LabelFor(model => model.reqDate, htmlAttributes: new { @class = "col-md-2" })

        @Html.EditorFor(model => model.reqDate, new { htmlAttributes = new { @readonly = "readonly", @id = "reqDate", @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.reqDate, "", new { @class = "text-danger" })

    </div>


   <div class="form-group">
        @Html.LabelFor(model => model.count, htmlAttributes: new { @class = "col-md-2" })
       <text> @Html.Encode(Model.items.Count()) </text>
    </div>


    <div class="form-group">
        @Html.LabelFor(model => model.reqNumber, htmlAttributes: new { @class = "col-md-2" })

        @Html.EditorFor(model => model.reqNumber, new { htmlAttributes = new { @readonly = "readonly", @id = "reqnum", @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.reqNumber, "", new { @class = "text-danger" })

    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.department, htmlAttributes: new { @class = "col-md-2" })

        @*@Html.EditorFor(model => model.department, new { htmlAttributes = new { @class = "form-control" } })*@
        @Html.DropDownListFor(model => model.department, new SelectList(Model.departmentsList, "Text", "Value"), new { @id = "department", @class = "form-control" })
        @Html.ValidationMessageFor(model => model.department, "", new { @class = "text-danger" })

    </div>


    <div class="form-group">
        @Html.LabelFor(model => model.employeeDetails, htmlAttributes: new { @class = "col-md-2" })
        @*@Html.Label("Requested by:", htmlAttributes: new { @class = "col-md-2" })*@
        @if (Model.department == null)
        {
            @Html.DropDownListFor(model => model.employeeDetails.employeeNum, new SelectList(string.Empty, "Value", "Text"), new { @id = "empname", @class = "form-control" })
        }
        else
        {
            @Html.DropDownListFor(model => model.employeeDetails.employeeNum, new SelectList(ViewBag.ReceivedByReps, "Value", "Text"), "select", new { @id = "empname", @class = "form-control" })
        }

        @*@Html.EditorFor(model => model.employeeName, new { htmlAttributes = new { @class = "form-control" } })*@
        @Html.ValidationMessageFor(model => model.employeeDetails.employeeNum, "", new { @class = "text-danger" })


    </div>


    @*@Html.DropDownListFor(model => model.employeeDetails.employeeNum, new SelectList((System.Collections.IEnumerable)TempData["company_dd3"], "Value", "Text"), "select", new { @class = "form-control" })*@

    @Html.HiddenFor(m => m.employeeDetails.firstName)
    @Html.HiddenFor(m => m.employeeDetails.lastName)
    @Html.HiddenFor(m => m.employeeDetails.Name)




    <fieldset class="form-group">
        <div class="form-horizontal">
            <h4>Enter Requested Item(s)</h4>

            <hr />

            <div class="Row form-group">
                <div class="col-md-5">
                    @Html.LabelFor(model => model.item.itemNumber, htmlAttributes: new { @class = "col-md-3" })
                    @Html.TextBoxFor(model => model.item.itemNumber, null, new { @readonly = "readonly", @id = "itemNumber", @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.item.itemNumber, "", new { @class = "text-danger" })
                </div>

                <div class="col-md-5">
                    @Html.LabelFor(model => model.item.description, htmlAttributes: new { @class = "col-md-3" })
                    @Html.TextBoxFor(model => model.item.description, null, new { @id = "description", @class = "form-control" })
                    @*<font color="blue">Please use your keyboard arrow keys to select items</font>*@
                    @*  @Html.EditorFor(model => model.item.description, new { @class = "control-label col-md-2", @id = "txtItem" })*@
                    @Html.ValidationMessageFor(model => model.item.description, "", new { @class = "text-danger" })
                   <font color="red">@ViewBag.errorMessage</font>
                </div>
            </div>

            @Html.HiddenFor(m => m.item.lineNum)




            <div class="Row  form-group">
                <div class="col-md-5">
                    @Html.LabelFor(model => model.item.price, htmlAttributes: new { @class = "col-md-3" })
                    @Html.TextBoxFor(model => model.item.price, new { @readonly = "readonly", @id = "price", @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.item.price, "", new { @class = "text-danger" })
                </div>

                <div class="col-md-5">
                    @Html.LabelFor(model => model.item.expense_account, htmlAttributes: new { @class = "col-md-3" })
                    @Html.DropDownListFor(model => model.item.expense_account.index, new SelectList(Model.accountlist, "Value", "Text"), new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.item.expense_account, "", new { @class = "text-danger" })

                </div>


                @Html.HiddenFor(model => model.item.selecteduomtext, new { @id = "selecteduomtext" })
                @Html.HiddenFor(model => model.item.lineNum)
                @Html.HiddenFor(model => model.items)


                <div class="col-md-5">
                    @Html.LabelFor(model => model.item.quantity, htmlAttributes: new { @class = "col-md-3" })
                    @Html.EditorFor(model => model.item.quantity, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.item.quantity, "", new { @class = "text-danger" })
                </div>

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

                    <div class="col-md-5">
                        @Html.LabelFor(model => model.item.UofM, htmlAttributes: new { @class = "col-md-3" })
                        @Html.DropDownListFor(model => model.item.UofM, new SelectList(string.Empty, "Text", "Value"), new { @id = "uofm", @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.item.UofM, "", new { @class = "text-danger" })
                    </div>



                </div>


                <div class="form-group">
                    <div class="col-md-offset-4 col-md-12">

                        <input type="submit" value="Add" name="Add" class="btn btn-default" width="89" />
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

                        <input type="button" value="Cancel" name="Cancel" margin="50px" onclick="location.href='@Url.Action("Cancel", "Requisition")' " class="btn btn-default" />


                    </div>
                </div>


                <div class="form-group">
                    <table id="myTable">
                        <tr>
                            <th class="col-md-2">Item Number</th>
                            <th class="col-md-2">Item Description</th>
                            <th class="col-md-3">Expense Account</th>
                            <th class="col-sm-1">Quantity</th>
                            <th class="col-sm-1">UOM</th>

                            <th class="col-sm-1">Item Price</th>


                            <th></th>
                        </tr>
                        @{

                                if (@Model.items.Count > 0)
                                {
                                    foreach (var item in @Model.items)
                                    {
                                        <tr>
                                            <td class="col-md-3">@item.itemNumber</td>
                                            <td class="col-md-2">@item.description</td>
                                            <td class="col-md-3">@item.expense_account.getDescription</td>
                                            <td class="col-sm-1">@item.quantity.ToString()</td>
                                            <td class="col-sm-1">@item.selecteduomtext</td>

                                            <td class="col-sm-1">@item.price.ToString()</td>



                                            <td>
                                                @Html.ActionLink("Edit", "Edit", new { id = item.lineNum }) |
                                                @Html.ActionLink("Remove", "Remove", new { id = item.lineNum }, new { onclick = "return confirm('Are you sure you would like to remove this item?'); " })
                                            </td>

                                        </tr>


                                }

                            }
                        }


                    </table>


                </div>



                <div class="form-group">
                    <div class="col-md-offset-4 col-md-12">


                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        @*<input type="button" value="Finish" name="Issue" margin="50px" onclick="location.href='/Requisition/ViewRequisition' " class="btn btn-default" />*@
                        <input type="button" id="RequestItem" value="Request" name="Request"  class="btn btn-default" />

Controller

[HttpPost]
public ActionResult RequestItem(Requisition requisition)
{
    IssueDAO dbdata = new IssueDAO();
    dbdata.connectionString = ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ConnectionString;
    getRequisition.reqDate = DateTime.Now; //Sets the transaction date to current date
    //getIssue.status = -1;
    Item item = new Item();
    try
    {
        dbdata.createRequisition(getRequisition, item);//Creates the issue in the database
    }
    catch (Exception ex)
    {
        LogWrite logWriter = new LogWrite(ex.ToString());
        ViewBag.errorMessage = "Unable to complete the Issue. Please see Log file for more Information";
        return View("RequisitionItem", getRequisition);
    }
    return View("RequisitionItem", getRequisition);
}

createRequisition Function

 public bool createRequisition(Requisition requisition, Item requisitionitem)
{
    int rec_upd = 0;
    bool status;
    using (SqlConnection TWCLOPConnect = new SqlConnection(connectionString.ToString()))
    {
    SqlCommand command = new SqlCommand();
    SqlCommand requestcommand = new SqlCommand();

    //Command to update the requisition table with the header information
    requestcommand.Connection = TWCLOPConnect;
    requestcommand.CommandType = CommandType.StoredProcedure;
    requestcommand.CommandText = "requisition_sp_createRequestion";
    //issuecommand.Parameters.Add("@docnum", SqlDbType.VarChar).Value = issue.docNumber;
    //issuecommand.Parameters.Add("@doctype", SqlDbType.VarChar).Value = issue.docType;
    requestcommand.Parameters.Add("@req_num", SqlDbType.VarChar).Value = requisition.reqNumber;
    //issuecommand.Parameters.Add("@stores_rep_id", SqlDbType.VarChar).Value = issue.processedbyDetails.employeeNum;
    //issuecommand.Parameters.Add("@dept_rep_id", SqlDbType.VarChar).Value = issue.employeeDetails.employeeNum;
    //issuecommand.Parameters.Add("@inventory_acc_indx", SqlDbType.Int).Value = issue.inventory_acccount;
    requestcommand.Parameters.Add("@description", SqlDbType.Int).Value =requisitionitem.description;
    requestcommand.Parameters.Add("@Req_Date", SqlDbType.DateTime).Value = requisition.reqDate;
    requestcommand.Parameters.Add("@qty", SqlDbType.Float);
    //issuecommand.Parameters.Add("@department", SqlDbType.VarChar).Value = issue.department;
    //issuecommand.Parameters.Add("@status", SqlDbType.Int).Value = issue.status;

    //Command to update the issueitem table with details of the transaction 
    command.Connection = TWCLOPConnect;
    command.CommandType = CommandType.StoredProcedure;
    command.CommandText = "createRequestedItem";
    command.Parameters.Add("@req_num", SqlDbType.VarChar).Value = requisition.reqNumber;
    //command.Parameters.Add("@inventory_acc_indx", SqlDbType.Int).Value = requisition.inventory_account;
    //command.Parameters.Add("@line_num", SqlDbType.Int);
    command.Parameters.Add("@itemnum", SqlDbType.VarChar);
    command.Parameters.Add("@qty", SqlDbType.Float);
    command.Parameters.Add("@issue_price", SqlDbType.Float);
    command.Parameters.Add("@expense_acc", SqlDbType.Int);
    //command.Parameters.Add("@inventory_acc", SqlDbType.Int);
    command.Parameters.Add("@uofm", SqlDbType.VarChar);
    try
    {
        TWCLOPConnect.Open();
        requestcommand.ExecuteNonQuery();
        foreach (var item in requisition.items)
        {
            //command.Parameters["@line_num"].Value = item.lineNum;
            command.Parameters["@itemnum"].Value = item.itemNumber;
            command.Parameters["@issue_price"].Value = item.price;
            command.Parameters["@qty"].Value = item.quantity;
            command.Parameters["@expense_acc"].Value = item.expense_account.index;
            //command.Parameters["@inventory_acc"].Value = item.inventory_account.index;
            command.Parameters["@uofm"].Value = item.selecteduomtext.Trim();
            rec_upd = command.ExecuteNonQuery();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        TWCLOPConnect.Close();
    }
    if (rec_upd > 0)
    {
        status = true;
    }
    else
    {
        status = false;
    }
}
return status;

}

Stored Procedures

      CREATE PROCEDURE createrequesteditem
            @expense_acc varchar(50),
            @quantity_requested int,
            @inventory_acc varchar(50),
            @Req_No varchar(50),
            @unit_of_measure varchar(15), 
            @issue_price float
        AS
        BEGIN
            -- SET NOCOUNT ON added to prevent extra result sets from
            -- interfering with SELECT statements.
            SET NOCOUNT ON;

            -- Insert statements for procedure here
            Insert Into RequestedItem Values (
                @expense_acc, 
                @quantity_requested ,
                @inventory_acc ,
                @Req_No ,
                @unit_of_measure, 
                @issue_price );
        END

    CREATE PROCEDURE requisition_sp_createRequisition
            @Req_No varchar(50),    
            @Req_Date datetime,
            @description varchar,
            @quantity int
        AS
        BEGIN
            -- SET 

NOCOUNT ON added to prevent extra result sets from
        -- interfering with SELECT statements.
        SET NOCOUNT ON;

        -- Insert statements for procedure here
        INSERT INTO Requisition VALUES (@Req_No,    
        @Req_Date, 
        @description,
        @quantity )
    END

1 个答案:

答案 0 :(得分:0)

After adding values to your stored procedure parameters, you should have the following commands:

command.Connection.Open();
command.ExecuteReader();
command.Connection.Close();

to open the connection, execute the stored procedure, then close the connection.