locked
Request.Form["ReasonForRejection"]; RRS feed

  • Question

  • User1975269135 posted

    Hello,

    I have a problem with the "Request.Form["ReasonForRejection"];" it give not a value back when I enter it in the screen.

    I hope someone can help me.

    With regards,

    Ronald

    Here is my code:

    @{
        Layout = "~/_SiteLayout.cshtml";
        Page.Title = "Declaration - Approve";
    
        var db = Database.Open("BCdecl");
            
        var DHId = UrlData[0];
        var DRId = UrlData[1];
        var Approve = "";
        
        // get DeclarationHeaders
        var queryDeclarationHeaders = "SELECT * FROM DeclarationHeaders JOIN Status ON DeclarationHeaders.StatusId = Status.StatusId JOIN UserProfile ON UserProfile.UserId = DeclarationHeaders.DHUserId JOIN Months ON DeclarationHeaders.DHPeriodMonth = Months.MonthId WHERE DHId=@0";
        var header = db.QuerySingle(queryDeclarationHeaders, DHId);
    
        // get DeclarationRows
        // var DRId= 0;
        var queryDeclarationRows = "SELECT * FROM DeclarationRows JOIN Exams ON DeclarationRows.ExamId = Exams.ExamId JOIN Locations ON DeclarationRows.LocationId = Locations.LocationId JOIN Status ON DeclarationRows.DRStatusId = Status.StatusId WHERE DHId=@0 ORDER BY DHId ASC, DRId ASC";
    
        // get FirstName DRApproved
        var queryFirstname = "SELECT FirstName FROM UserProfile ORDER BY UserId";
        // var firstname = db.Query(queryFirstname);
        
        // Processing
        if (Approve == "Yes")
        {   
                var DRApproved = "Yes";
                var DRApprovedUserId = @WebSecurity.CurrentUserId;
                var DRApprovedDate = DateTime.Now.ToString("dd-MM-yyyy");
                var DRStatusId = "2";
    
                // update Rows
                var updateRow = "UPDATE DeclarationRows SET DRApproved=@0, DRApprovedUserId=@1, DRApprovedDate=@2, DRStatusId=@3 WHERE DRId=@4";
                db.Execute(updateRow, DRApproved, DRApprovedUserId, DRApprovedDate, DRStatusId, DRId);
    
                Response.Redirect(@Href("~/Users/Declaration-Approve/" + @header.DHId));
        }
    
        if (Approve == "No")
        {   
                // Setup validation
                Validation.Add("ReasonForRejection",
                Validator.Required("The reason for rejection is required"),
                Validator.StringLength(200, 1, "The reason for rejection is required"));
                var ReasonForRejection = Request.Form["ReasonForRejection"];
         
                if (Validation.IsValid()) {
                    var DRApproved = "No";
                    var DRApprovedUserId = @WebSecurity.CurrentUserId;
                    var DRApprovedDate = DateTime.Now.ToString("dd-MM-yyyy");
                    var DRStatusId = "4";
                    ReasonForRejection = Request.Form["ReasonForRejection"];
    
                    // update Rows
                   var updateRow = "UPDATE DeclarationRows SET DRApproved=@0, DRApprovedUserId=@1, DRApprovedDate=@2, DRStatusId=@3, ReasonForRejection=@4 WHERE DRId=@5";
                db.Execute(updateRow, DRApproved, DRApprovedUserId, DRApprovedDate, DRStatusId, ReasonForRejection, DRId);
    
                    Response.Redirect(@Href("~/Users/Declaration-Approve/" + @header.DHId));
                }
                
        }
    }
    
    <h1>@Page.Title</h1>
    
    <!DOCTYPE html>
    
    <html>
    <body>
        <form method="post" action="" enctype="multipart/form-data">
        @if (WebSecurity.IsAuthenticated)
        {
            
            <table id="tableBC">
            <tr>
                <th width="70px">Date</th>
                <th width="60px">Exam</th>
                <th width="60px">Working hours</th>
                <th width="60px">Extra hours</th>
                <th width="60px">Travel-ling hours</th>
                <th width="60px">KM travelled car</th>
                <th width="60px">Public transport costs</th>
                <th width="120px">Location</th>
                <th width="150px">Comments</th>
                <th width="60px">Status Approve</th>
                <th width="260px">Action(s) <br /> Approve or Edit <br /> and Reason for rejection</th>
                <th width="100px">BC User info</th>
            </tr>
            @foreach (var row in db.Query(queryDeclarationRows, DHId))
            {   
                <tr>
                    <!-- display Rows -->
                    <td>@row.DRDate</td>
                    <td>@row.Examcode</td>
                    @if (@row.DRWorkingHoursDecimal == 0)
                    {
                        <td class="right">@row.DRWorkingHours:00</td>
                    }
                    else
                    {
                        <td class="right">@row.DRWorkingHours:@row.DRWorkingHoursDecimal</td>
                    }
                    @if (@row.DRExtraHoursDecimal == 0)
                    {
                        <td class="right">@row.DRExtraHours:00</td>
                    }
                    else
                    {
                        <td class="right">@row.DRExtraHours:@row.DRExtraHoursDecimal</td>
                    }
                    @if (@row.DRTravellingHoursDecimal == 0)
                    {
                        <td class="right">@row.DRTravellingHours:00</td>
                    }
                    else
                    {
                        <td class="right">@row.DRTravellingHours:@row.DRTravellingHoursDecimal</td>
                    }
                    <td class="right">@row.DRKM</td>
                    <td class="right">€ @row.DRPublicTransportCosts</td>
                    <td>@row.LocationName  - @row.LocationCity</td>
                    <td>@row.DRComments</td>
                    <!--<td>AAPi</td>-->
                    <!--<td>@row.DRid</td>-->
                    <td>@row.DRApproved</td>
                      
                    <td>
                        <a href="~/Users/Declaration-Approve/@row.DHId/@row.DRId/Yes">Yes</a><br />
                        <input type="text" class="inputReasonForRejection" name="ReasonForRejection" placeholder="if No, then reason required" value="@row.ReasonForRejection"  />
                        <a href="~/Users/Declaration-Approve/@row.DHId/@row.DRId/No">No</a><!--onclick = "return openInNewWindow(this)-->
                        <br />@Html.ValidationMessage("ReasonForRejection")
                    </td>
                    <td>@row.DRApprovedDate<br /> @if (@row.DRApprovedUserId != null){var firstname = db.QuerySingle(queryFirstname, @row.DRApprovedUserId);@firstname.FirstName}</td>
                </tr>
               
             } 
            
        </table>
                
        }
        </form>
        
    </body>
    </html>
    



    Sunday, January 11, 2015 6:05 AM

Answers

  • User281315223 posted

    You may need to check and ensure that an actual POST operation occurred so that you can access those values within your code by using the IsPost property :

    @{
         // Check if a Post occurred
         if(IsPost)
         {
              // Apply your logic and check for Form variables here (e.g. Form.Request["YourProperty"])
         }
         else
         {
              // Otherwise this is an initial load and likely will not contain any Form variables
         }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, January 11, 2015 8:10 AM
  • User-821857111 posted

    You don't provide any means for submitting your form that I can see. After the closing </table> tag, you should add a submit button:

    <input type="submit" />

    There is another problem lurking - you will have multiple fields with the same name value, so their values will be presented in the Request.Form collection as a comma-separated string. You could use the string.Split method to convert that to an array ans then try to work out which value belongs to which row based on its index in the resulting array, or you can make sure that each ReasonForRejection field has a unique name by appending the row's ID value to the name:

    <input type="text" class="inputReasonForRejection" name="@("ReasonForRejection" + row.DRId)" ...

    Then you can get all the values like this:

    foreach(string item in Request.Form)
    {
        if(item.StartsWith("ReasonForRejection"))
        {
            //found one - just need to see which ID it belongs to
            var currentId = item.Replace("ReasonForRejection", "").AsInt();
            var currentValue = Request[item];
        }
    }



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, January 11, 2015 12:56 PM
  • User1080785583 posted

    ValidationAttribute, IClientValidatable will help you with 'business rules' here is a small example of how i did it for a product called, bench.

     public class BenchAttribute : ValidationAttribute, IClientValidatable
        {
            private const decimal PlaqueLength = 36;
    
            public string Length { get { return PlaqueLength.ToString(CultureInfo.InvariantCulture); } }
    
            public BenchAttribute()
            {
                ErrorMessage = string.Format("{0} {1} {2}", "Plaque cannot exceed", PlaqueLength, "characters.");
            }
    
    
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
                ValidationResult validationResult = ValidationResult.Success;
                if (value == null)
                {
                    return new ValidationResult("Inscription Required.");
                }
    
                if (value.ToString().Length > PlaqueLength)
                {
                    validationResult = new ValidationResult(ErrorMessage);
                }
    
                return validationResult;
            }
    
            public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
            {
                var rule = new ModelClientValidationRule
                {
                    ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                    ValidationType = "bench",
                };
                rule.ValidationParameters.Add("length", PlaqueLength);
                yield return rule;
            }
        }
    public class ProductViewModel : IProductViewModel 
    { 
            [Bench]
            public string BenchThisInput { get; set; }
    }
    
    .cshtml view
    @model kewlnamespace.ProductViewModel
    @using (Html.BeginForm("ProductFormView", "Product", FormMethod.Post)
    {
    @Html.ValidationSummary("Invalid input!");
    @Html.TextBoxFor(f => f.BenchThisInput)
    <input type ='submit' value='dowork' />


    so now when you post the object to the server, you check if(Modelstate.IsValid) and then your error will be part of your modelState .

    see https://www.captechconsulting.com/blog/handling-multiple-validation-rules-aspnet-mvc-using-dataannotations-and-unobtrusive-jquery-0 for more clarity...

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 21, 2015 11:45 AM

All replies

  • User281315223 posted

    You may need to check and ensure that an actual POST operation occurred so that you can access those values within your code by using the IsPost property :

    @{
         // Check if a Post occurred
         if(IsPost)
         {
              // Apply your logic and check for Form variables here (e.g. Form.Request["YourProperty"])
         }
         else
         {
              // Otherwise this is an initial load and likely will not contain any Form variables
         }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, January 11, 2015 8:10 AM
  • User1975269135 posted

    Hi Rion,

    Thanks for the info, I have made some modifications but it still working because IsPost stays "false"

    @{
        Layout = "~/_SiteLayout.cshtml";
        Page.Title = "Declaration - Approve";
    
        var db = Database.Open("BCdecl");
            
        var DHId = UrlData[0];
        var DRId = UrlData[1];
        var Approve = UrlData[2];
        
        // get DeclarationHeaders
        var queryDeclarationHeaders = "SELECT * FROM DeclarationHeaders JOIN Status ON DeclarationHeaders.StatusId = Status.StatusId JOIN UserProfile ON UserProfile.UserId = DeclarationHeaders.DHUserId JOIN Months ON DeclarationHeaders.DHPeriodMonth = Months.MonthId WHERE DHId=@0";
        var header = db.QuerySingle(queryDeclarationHeaders, DHId);
    
        // get DeclarationRows
        // var DRId= 0;
        var queryDeclarationRows = "SELECT * FROM DeclarationRows JOIN Exams ON DeclarationRows.ExamId = Exams.ExamId JOIN Locations ON DeclarationRows.LocationId = Locations.LocationId JOIN Status ON DeclarationRows.DRStatusId = Status.StatusId WHERE DHId=@0 ORDER BY DHId ASC, DRId ASC";
    
        // get FirstName DRApproved
        var queryFirstname = "SELECT FirstName FROM UserProfile ORDER BY UserId";
        // var firstname = db.Query(queryFirstname);
        
        // Setup validation
        Validation.Add("ReasonForRejection",
        Validator.Required("The reason for rejection is required"),
        Validator.StringLength(200, 1, "The reason for rejection is required"));
        
        // Processing
        if (IsPost)
        {
            var ReasonForRejection = Request.Form["ReasonForRejection"];
        }
    
        else
        {
            if (Approve == "Yes")
            {
                var DRApproved = "Yes";
                var DRApprovedUserId = @WebSecurity.CurrentUserId;
                var DRApprovedDate = DateTime.Now.ToString("dd-MM-yyyy");
                var DRStatusId = "2";
    
                // update Rows
                var updateRow = "UPDATE DeclarationRows SET DRApproved=@0, DRApprovedUserId=@1, DRApprovedDate=@2, DRStatusId=@3 WHERE DRId=@4";
                db.Execute(updateRow, DRApproved, DRApprovedUserId, DRApprovedDate, DRStatusId, DRId);
    
                Response.Redirect(@Href("~/Users/Declaration-Approve-Forum/" + @header.DHId));
            }
    
            if (Approve == "No")
            {
                // if (Validation.IsValid())
                // {
                    var DRApproved = "No";
                    var DRApprovedUserId = @WebSecurity.CurrentUserId;
                    var DRApprovedDate = DateTime.Now.ToString("dd-MM-yyyy");
                    var DRStatusId = "4";
                    var ReasonForRejection = Request.Form["ReasonForRejection"];
    
                    // update Rows
                    var updateRow = "UPDATE DeclarationRows SET DRApproved=@0, DRApprovedUserId=@1, DRApprovedDate=@2, DRStatusId=@3, ReasonForRejection=@4 WHERE DRId=@5";
                    db.Execute(updateRow, DRApproved, DRApprovedUserId, DRApprovedDate, DRStatusId, ReasonForRejection, DRId);
    
                    Response.Redirect(@Href("~/Users/Declaration-Approve-Forum/" + @header.DHId));
                // }
    
            }
        }
        
    }
    
    <h1>@Page.Title</h1>
    
    <!DOCTYPE html>
    
    <html>
    <body>
        <form method="post" action="" enctype="multipart/form-data">
        @if (WebSecurity.IsAuthenticated)
        {
            
            <table id="tableBC">
            <tr>
                <th width="70px">Date</th>
                <th width="60px">Exam</th>
                <th width="60px">Working hours</th>
                <th width="60px">Extra hours</th>
                <th width="60px">Travel-ling hours</th>
                <th width="60px">KM travelled car</th>
                <th width="60px">Public transport costs</th>
                <th width="120px">Location</th>
                <th width="150px">Comments</th>
                <th width="60px">Status Approve</th>
                <th width="260px">Action(s) <br /> Approve or Edit <br /> and Reason for rejection</th>
                <th width="100px">BC User info</th>
            </tr>
            @foreach (var row in db.Query(queryDeclarationRows, DHId))
            {   
                <tr>
                    <!-- display Rows -->
                    <td>@row.DRDate</td>
                    <td>@row.Examcode</td>
                    @if (@row.DRWorkingHoursDecimal == 0)
                    {
                        <td class="right">@row.DRWorkingHours:00</td>
                    }
                    else
                    {
                        <td class="right">@row.DRWorkingHours:@row.DRWorkingHoursDecimal</td>
                    }
                    @if (@row.DRExtraHoursDecimal == 0)
                    {
                        <td class="right">@row.DRExtraHours:00</td>
                    }
                    else
                    {
                        <td class="right">@row.DRExtraHours:@row.DRExtraHoursDecimal</td>
                    }
                    @if (@row.DRTravellingHoursDecimal == 0)
                    {
                        <td class="right">@row.DRTravellingHours:00</td>
                    }
                    else
                    {
                        <td class="right">@row.DRTravellingHours:@row.DRTravellingHoursDecimal</td>
                    }
                    <td class="right">@row.DRKM</td>
                    <td class="right">€ @row.DRPublicTransportCosts</td>
                    <td>@row.LocationName  - @row.LocationCity</td>
                    <td>@row.DRComments</td>
                    <!--<td>AAPi</td>-->
                    <!--<td>@row.DRid</td>-->
                    <td>@row.DRApproved</td>
                      
                    <td>
                        <a href="~/Users/Declaration-Approve-Forum/@row.DHId/@row.DRId/Yes">Yes</a><br />
                        <input type="text" class="inputReasonForRejection" name="ReasonForRejection" placeholder="if No, then reason required" value="@row.ReasonForRejection"  />
                        <a href="~/Users/Declaration-Approve-Forum/@row.DHId/@row.DRId/No">No</a>
                        <br />@Html.ValidationMessage("ReasonForRejection")
                    </td>
                    <td>@row.DRApprovedDate<br /> @if (@row.DRApprovedUserId != null){var firstname = db.QuerySingle(queryFirstname, @row.DRApprovedUserId);@firstname.FirstName}</td>
                </tr>
               
             } 
            
        </table>
                
        }
        </form>
        
    </body>
    </html>
    



    Sunday, January 11, 2015 10:10 AM
  • User-821857111 posted

    You don't provide any means for submitting your form that I can see. After the closing </table> tag, you should add a submit button:

    <input type="submit" />

    There is another problem lurking - you will have multiple fields with the same name value, so their values will be presented in the Request.Form collection as a comma-separated string. You could use the string.Split method to convert that to an array ans then try to work out which value belongs to which row based on its index in the resulting array, or you can make sure that each ReasonForRejection field has a unique name by appending the row's ID value to the name:

    <input type="text" class="inputReasonForRejection" name="@("ReasonForRejection" + row.DRId)" ...

    Then you can get all the values like this:

    foreach(string item in Request.Form)
    {
        if(item.StartsWith("ReasonForRejection"))
        {
            //found one - just need to see which ID it belongs to
            var currentId = item.Replace("ReasonForRejection", "").AsInt();
            var currentValue = Request[item];
        }
    }



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, January 11, 2015 12:56 PM
  • User1975269135 posted

    Hi Mike,

    I tried what you said, but it does not work.

    What I want to get done is that there is a rule approved in a (yes) or rejected (No) can be specified with the reason of rejection.
    Saving the rekord with Yes and No is going well, I get only not the reason or reject it.
    Maybe you can help me out with a possible solution.

    Tuesday, January 13, 2015 1:44 PM
  • User1080785583 posted

    ValidationAttribute, IClientValidatable will help you with 'business rules' here is a small example of how i did it for a product called, bench.

     public class BenchAttribute : ValidationAttribute, IClientValidatable
        {
            private const decimal PlaqueLength = 36;
    
            public string Length { get { return PlaqueLength.ToString(CultureInfo.InvariantCulture); } }
    
            public BenchAttribute()
            {
                ErrorMessage = string.Format("{0} {1} {2}", "Plaque cannot exceed", PlaqueLength, "characters.");
            }
    
    
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
                ValidationResult validationResult = ValidationResult.Success;
                if (value == null)
                {
                    return new ValidationResult("Inscription Required.");
                }
    
                if (value.ToString().Length > PlaqueLength)
                {
                    validationResult = new ValidationResult(ErrorMessage);
                }
    
                return validationResult;
            }
    
            public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
            {
                var rule = new ModelClientValidationRule
                {
                    ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                    ValidationType = "bench",
                };
                rule.ValidationParameters.Add("length", PlaqueLength);
                yield return rule;
            }
        }
    public class ProductViewModel : IProductViewModel 
    { 
            [Bench]
            public string BenchThisInput { get; set; }
    }
    
    .cshtml view
    @model kewlnamespace.ProductViewModel
    @using (Html.BeginForm("ProductFormView", "Product", FormMethod.Post)
    {
    @Html.ValidationSummary("Invalid input!");
    @Html.TextBoxFor(f => f.BenchThisInput)
    <input type ='submit' value='dowork' />


    so now when you post the object to the server, you check if(Modelstate.IsValid) and then your error will be part of your modelState .

    see https://www.captechconsulting.com/blog/handling-multiple-validation-rules-aspnet-mvc-using-dataannotations-and-unobtrusive-jquery-0 for more clarity...

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 21, 2015 11:45 AM
  • User-821857111 posted

    What I want to get done is that there is a rule approved in a (yes) or rejected (No) can be specified with the reason of rejection.
    Saving the rekord with Yes and No is going well, I get only not the reason or reject it.
    Maybe you can help me out with a possible solution.

    I'm not at all clear what you want.

    Friday, January 23, 2015 10:18 AM