You must Sign In to post a response.
  • Category: ASP.Net MVC

    How to insert data into database for a row containing data only in mvc

    hi all below is my code i have addnewrow button so when i click on add new row for 4 times 4 rows will come so in that i have added values for one row remaining rows has no no dat so when i click on save button all 4 rows are inserting i want only to insert only row containing data

    in view.cshtml
    function validateIncome(){
    var flgSave = false;
    var flgIsEdit = false;
    var RowCnt=0;
    var VaildRowCnt=0;

    $("#incomeGridB >tbody >tr").each(function () {
    var tr = $(this);
    var displayMode = tr.find("td > label").css("display");
    if (displayMode == 'inline-block' || displayMode == 'block') {
    RowCnt ++;
    flgIsEdit = true;



    if(tr.find("#customer").val()=="Select" && tr.find("#plnContract").val()=="Select" && tr.find("#plnContractNo").val().trim()=="" && !flgMonthValPresent )
    {
    //$('incomeGridB > tbody > tr').not(':first').not(':last').addClass('highlight');
    return true;
    flgSave=false;

    } if(tr.find("#customer").val()=="Select"){
    displayAlert("Please select the customer.");
    return false;
    }
    if(tr.find("#plnContract").val()=="Select"){
    displayAlert("Please select the contract status.");
    return false;
    }
    if(tr.find("#plnContractNo").val().trim()==""){
    displayAlert("Please enter the contract number.");
    return false;
    }
    if(tr.find("#strtMnth").val()=="Select"){
    displayAlert("Please select the start month.");
    return;
    }
    if(tr.find("#endMnth").val()=="Select"){
    displayAlert("Please select the end month.");
    return false;
    }
    if(tr.find("#endMnth").prop('selectedIndex')<tr.find("#strtMnth").prop('selectedIndex')){
    displayAlert("End month should be greater than start month.");
    return false;
    }

    var flgMonthValPresent = false;
    for(var i=1;i<=12;i++){
    if(tr.find("#month"+i).val().trim()!=""){
    flgMonthValPresent = true;
    }
    }
    if(!flgMonthValPresent){
    displayAlert("Please enter the amount for atleast one month.");
    return false;
    }
    VaildRowCnt++;
    }
    // flgSave=true;
    });
    if(RowCnt ==VaildRowCnt){
    flgSave = true;
    }
    if(toDelete.length>0 && flgIsEdit==false){
    flgSave = true;
    flgIsEdit = true;
    }

    if(!flgIsEdit){
    displayAlert("There is no data entered/modified to save.");
    flgSave = false;
    }
    return flgSave;
    }

    addnewrow

    function addNewRow() {
    td = "";
    //Column definition
    var columnDef = [
    {
    "name": "incomePlanId",
    "id": "incmPlnId",
    "class" : "edit-mode",
    "type" : "label",
    "value" : " ",
    "option" : "",
    "style" : "display: inline-block;"
    },
    {
    "name" : "customer",
    "id" : "customer",
    "class" : "edit-mode",
    "type": "select",
    "value" : " ",
    "option" : "",
    "style" : "display: inline-block;"
    },
    {
    "name": "contractStatus",
    "id": "plnContract",
    "class": "edit-mode",
    "type": "select",
    "value": " ",
    "option": "",
    "style": "display: inline-block;min-width:100px;"
    },
    {
    "name": "contractNo",
    "id": "plnContractNo",
    "class": "edit-mode",
    "type": "text",
    "value": " ",
    "option": "",
    "style": "display: inline-block;",
    "onkeyup" : " "
    },
    {
    "name": "strtMnth",
    "id": "strtMnth",
    "class": "edit-mode",
    "type": "select",
    "value": " ",
    "option": "",
    "style": "display: inline-block;min-width:100px;"
    },
    {
    "name": "endMnth",
    "id": "endMnth",
    "class": "edit-mode",
    "type": "select",
    "value": " ",
    "option": "",
    "style": "display: inline-block;min-width:100px;"
    },
    {
    "name" : "amount",
    "id": "month0",
    "class" : "edit-mode amount",
    "type" : "text",
    "value" : " ",
    "option" : "",
    "style" : "display: inline-block;",
    "attr" : "readonly",
    "onkeyup" : " "
    },
    {
    "name" : "month1",
    "id": "month1",
    "class" : "edit-mode amount",
    "type" : "text",
    "value" : " ",
    "option" : "",
    "style" : "display: inline-block;",
    "onchange" : "javascript:updateRowAmount(this);"
    },
    {
    "name": "month2",
    "id": "month2",
    "class": "edit-mode amount",
    "type": "text",
    "value": " ",
    "option": "",
    "style": "display: inline-block;",
    "onchange" : "javascript:updateRowAmount(this);"
    },
    {
    "name": "month3",
    "id": "month3",
    "class": "edit-mode amount",
    "type": "text",
    "value": " ",
    "option": "",
    "style": "display: inline-block;",
    "onchange" : "javascript:updateRowAmount(this);"
    },
    {
    "name": "month4",
    "id": "month4",
    "class": "edit-mode amount",
    "type": "text",
    "value": " ",
    "option": "",
    "style": "display: inline-block;",
    "onchange" : "javascript:updateRowAmount(this);"
    },
    {
    "name": "month5",
    "id": "month5",
    "class": "edit-mode amount",
    "type": "text",
    "value": " ",
    "option": "",
    "style": "display: inline-block;",
    "onchange" : "javascript:updateRowAmount(this);"
    },
    {
    "name": "month6",
    "id": "month6",
    "class": "edit-mode amount",
    "type": "text",
    "value": " ",
    "option": "",
    "style": "display: inline-block;",
    "onchange" : "javascript:updateRowAmount(this);"
    },
    {
    "name": "month7",
    "id": "month7",
    "class": "edit-mode amount",
    "type": "text",
    "value": " ",
    "option": "",
    "style": "display: inline-block;",
    "onchange" : "javascript:updateRowAmount(this);"
    },
    {
    "name": "month8",
    "id": "month8",
    "class": "edit-mode amount",
    "type": "text",
    "value": " ",
    "option": "",
    "style": "display: inline-block;",
    "onchange" : "javascript:updateRowAmount(this);"
    },
    {
    "name": "month9",
    "id": "month9",
    "class": "edit-mode amount",
    "type": "text",
    "value": " ",
    "option": "",
    "style": "display: inline-block;",
    "onchange" : "javascript:updateRowAmount(this);"
    },
    {
    "name": "month10",
    "id": "month10",
    "class": "edit-mode amount",
    "type": "text",
    "value": " ",
    "option": "",
    "style": "display: inline-block;",
    "onchange" : "javascript:updateRowAmount(this);"
    },
    {
    "name": "month11",
    "id": "month11",
    "class": "edit-mode amount",
    "type": "text",
    "value": " ",
    "option": "",
    "style": "display: inline-block;",
    "onchange" : "javascript:updateRowAmount(this);"
    },
    {
    "name": "month12",
    "id": "month12",
    "class": "edit-mode amount",
    "type": "text",
    "value": " ",
    "option": "",
    "style": "display: inline-block;",
    "onchange" : "javascript:updateRowAmount(this);"
    },
    {
    "name": "action",
    "id": "btnDelNew",
    "class": "deleteNew-incomePlan edit-mode",
    "type": "button",
    "value": "Delete",
    "option": "",
    "style": "display: inline-block;"
    }
    ];
    for(var i = 0; i<columnDef.length; i++)
    {
    var cell = columnDef[i];
    td += generateCell(cell);
    }
    var noRow = $("#incomeGridB >tbody >tr.noRow");
    if (noRow) {
    noRow.remove();
    }
    $('#incomeGridB tbody').append('<tr>' +
    td +
    '</tr>');
    getCustomerList();
    getContractStatusList();
    getAllMonths();
    setColReadOnly();
    triggerKeyPress();
    }

    my incomeupdatecontroller

    public async Task<ActionResult> UpdateIncome(List<income> incomeData, string deletionList, string EntryType, string RevisionNo)
    {
    income incm;
    Type incomeType = typeof(income);
    int entrytype = int.Parse(EntryType);
    if (RevisionNo == "Select" || RevisionNo == "" || entrytype == 1)
    RevisionNo = "0";
    if (!String.IsNullOrEmpty(deletionList))
    {
    int delPlanCount = await this.DeleteIncomePlan(deletionList);
    if (deletionList.Count() != delPlanCount)
    {
    System.Diagnostics.Debug.WriteLine("Comitted Delete count : {delPlanCount} / {deletionList.Count()}");
    }
    }
    if (incomeData != null)
    {
    string strLastUpdatedBy = Session[eBPConstants.LoggedGID].ToString();
    int FinYear = int.Parse(Session[eBPConstants.LoggedUserFinYear].ToString());
    var serializeIncome = incomeData;
    //Json data set to DB
    foreach (income incomePlanObj in serializeIncome)
    {
    if (incomePlanObj.Id == 0)
    {
    incm = new income();
    incm.Customer = incomePlanObj.Customer;
    incm.ContractStatus = incomePlanObj.ContractStatus;
    incm.ContractNo = incomePlanObj.ContractNo;
    incm.OrgId = incomePlanObj.OrgId;
    for (int i = 1; i <= 12; i++)
    {
    decimal? monthVal = (decimal?)incomeType.GetProperty($"Month{i}Val").GetValue(incomePlanObj);
    PropertyInfo monthValProp = incomeType.GetProperty($"Month{i}Val", BindingFlags.Public | BindingFlags.Instance);
    if (null != monthValProp && monthValProp.CanWrite)
    {
    monthValProp.SetValue(incm, monthVal, null);
    }
    }
    incm.FinYear = FinYear;
    incm.StartMonth = incomePlanObj.StartMonth;
    incm.EndMonth = incomePlanObj.EndMonth;
    //Required fields - DB(Not Null)
    incm.SoruceType = 2;
    incm.EntryType = entrytype;
    incm.Latest = 1;
    incm.RevisionNum = RevisionNo;
    incm.LastUpdate = System.DateTime.Now;
    incm.LastUpdateBy = strLastUpdatedBy;
    eBPEntities.incomes.Add(incm);
    }

    else
    {
    incm = eBPEntities.incomes.Single(inocme => inocme.Id == incomePlanObj.Id);
    if (incm != null)
    {
    incm.Customer = incomePlanObj.Customer;
    incm.ContractStatus = incomePlanObj.ContractStatus;
    incm.ContractNo = incomePlanObj.ContractNo;
    for (int i = 1; i <= 12; i++)
    {
    decimal? monthVal = (decimal?)incomeType.GetProperty($"Month{i}Val").GetValue(incomePlanObj);
    PropertyInfo monthValProp = incomeType.GetProperty($"Month{i}Val", BindingFlags.Public | BindingFlags.Instance);
    if (null != monthValProp && monthValProp.CanWrite)
    {
    monthValProp.SetValue(incm, monthVal, null);
    }
    }
    incm.FinYear = FinYear;
    incm.StartMonth = incomePlanObj.StartMonth;
    incm.EndMonth = incomePlanObj.EndMonth;
    //Required fields - DB(Not Null)
    incm.SoruceType = 2;
    incm.EntryType = entrytype;
    incm.Latest = 1;
    incm.RevisionNum = RevisionNo;
    incm.LastUpdate = System.DateTime.Now;
    incm.LastUpdateBy = strLastUpdatedBy;
    eBPEntities.Entry(incm).State = EntityState.Modified;
    }
    }
    }
    try
    {
    eBPEntities.SaveChanges();
    }
    catch (Exception ex)
    {
    eBPlogger.Error("An exception occured while save changes to Income!!", ex);
    return Json(new { msg = "An exception occured while save changes to Income!!", success = false });
    }
    }
    // if (incomeData == null)
    //{ return Json(new { msg = "Income updated Successfully!!", success = true });}
    return Json(new { msg = "Income updated Successfully!!", success = true });
    }
    }
  • #768432
    Hi,
    You can validate a row that it has data before inserting it to DB.

    Find MVC grid 'Client side and Server side' validation tricks for dynamically added rows over here:
    http://blog.stevensanderson.com/2010/01/28/validating-a-variable-length-list-aspnet-mvc-2-style/

    Or you can use Grid_RowValidating() event as follows:

    using DevExpress.Web.ASPxGridView;
    using System.Collections.Generic;

    protected void grid_RowValidating(object sender, DevExpress.Web.Data.ASPxDataValidationEventArgs e)
    {
    // Checks for null values.
    foreach (GridViewColumn column in grid.Columns)
    {
    GridViewDataColumn dataColumn = column as GridViewDataColumn;
    if (dataColumn == null) continue;
    if (e.NewValues[dataColumn.FieldName] == null)
    e.Errors[dataColumn] = "Value can't be null.";
    }
    // Displays the error row if there is at least one error.
    if (e.Errors.Count > 0)
    e.RowError = "Please, fill all the fields.";
    }


Sign In to post your comments