locked
Nullify input tags RRS feed

  • Question

  • User-309523270 posted

    Hi,

    I was trying to empty the contents the user entered after saving the first record.  However, I was not able to do so.  The app is still showing the entered values after a successful "Save"(a post).  I created a new model with null values in the controller before passing on to the view.  The model that I'm trying to nullify is an inner model(nested) of another model.  Also, the content I was trying to nullify is a nested view.  I also tried to null the values in jquery.  However, the app is not even showing the "alert" code in jquery of which the nullable jquery code is part.

    Code is below.

    Please advise.

    Thanks,

    tinac99

    Code
    =======================================

    Model
    =====================

        public class BOTEditViewModel
        {
            public BOTDTO botdto { get; set; }
            public BOTItemEntryViewModel BOTItemEntry { get; set; }
            public IEnumerable<BOTItemViewModel> BOTItemList { get; set; }
        }


        public class BOTDTO
        {
            [Display(Name = "Bill-of-Tools Number")]
            public string BotNumber { get; set; }

            [Display(Name = "Description")]
            public string BotNumberDesc { get; set; }

            [Display(Name = "Type")]
            public string BotType { get; set; }

            public virtual ICollection<BOTItemEntryViewModel> BotItem { get; set; }

        }


        public class BOTItemEntryViewModel
        {
        public string ParentId { get; set; }

            [Required]
            [Range(1, int.MaxValue, ErrorMessage = "Please enter Quantity greater than 0.")]
            public short ItemQuantity { get; set; }

            public MaterialEntryViewModel materialEntry { get; set; }
        }


        public class MaterialEntryViewModel
        {
            [StringLength(7)]
            [Display(Name = "Material Code")]
            public string MaterialCode { get; set; }

            [StringLength(150)]
            [Display(Name = "Material Description")]
            public string MaterialDescription { get; set; }

        }


    View
    ===============================
    Edit.cshtml
    -----------------------------------------------

    @using ToolsOracle.Business
    @model ToolsOracle.Data.ViewModel.BOTEditViewModel

    @{
        ViewData["Title"] = "Edit Bill-Of-Tools";
    }

    <h2>Bill of Tools Details</h2>

    <hr />

    <div>
        @Html.ValidationSummary(false, "", new { @class = "text-danger" })
        <center>
            <font color="red">@ViewBag.Message</font>
        </center>
        <br />
        <form asp-controller="BOTAdmin" method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            @Html.AntiForgeryToken()
            <div class="form-group" align="center">
                <table class="search-criteria">
                    <tr><td style="background-color:lightseagreen; color:white">Update Bill of Tool Information here.</td></tr>
                    <tr>
                        <td height="20px"></td>
                    </tr>
                    <tr>
                        <td class="text-indent" style="padding-right:50px">
                            @await Html.PartialAsync("_BOTEntryPartial", Model.botdto)
                        </td>
                    </tr>
                    <tr>
                        <td height="20px"></td>
                    </tr>
                    @if (User.IsInRole(UserRoles.TOOLROOM_ADMIN) || User.IsInRole(UserRoles.SYSTEM_ADMIN))
                    {
                        <tr>
                            <td align="center">
                                <input type="submit" value="Update" formaction="UpdateBOT" class="btn btn-info" />
                            </td>
                        </tr>
                    }
                    <tr>
                        <td height="20px"></td>
                    </tr>
                </table>
            </div>
        </form>
    </div>
    <br />
    <table class="search-criteria">
        <tr>
            <td style="background-color:lightseagreen; color:white">Add item to Bill of Tool here.</td>
        </tr>
        <tr>
            <td height="20px"></td>
        </tr>
        <tr>
            <td style="padding-left: 20px; padding-right:20px">
                @await Html.PartialAsync("_BOTItemsEntryPartial", Model.BOTItemEntry)
            </td>
        </tr>
    </table>
    <br />
    <br />


    @section Scripts {
        <script nws-csp-add-nonce="true">

            $(document).ready(function () {
                $("#BotNumber").prop("readonly", true);
            });

        </script>
        }

    _BOTItemsEntryPartial.cshtml
    ------------------------------------------
    @using ToolsOracle.Business
    @model ToolsOracle.Data.ViewModel.BOTItemEntryViewModel

    <form asp-controller="BOT" action="AddBOTItems" method="post">
        @Html.AntiForgeryToken()
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="BotAssignId" value="@Model.BotAssignId" class="form-control" />*@
        <input type="hidden" asp-for="ParentId" value="@Model.ParentId" class="form-control" />

        <table>
            <tr>
                <td valign="middle">
                    @await Html.PartialAsync("_MaterialsPartial", Model.materialEntry)
                </td>
                <td width="5px"></td>
                <td valign="middle">Quantity<font color="red">*</font></td>
                <td valign="middle">
                    <input asp-for="ItemQuantity" style="width:50px" />
                </td>
                <td width="5px"></td>
                <td valign="middle">
                    @if (User.IsInRole(UserRoles.TOOLROOM_CLERK) || User.IsInRole(UserRoles.TOOLROOM_ADMIN) || User.IsInRole(UserRoles.SYSTEM_ADMIN))
                    {
                        <input type="submit" name="AddBOTItems" value="Add Item" class="btn btn-info" />
                    }
                </td>
            </tr>
            <tr>
                <td colpan="6" height="10px"></td>
            </tr>
            <tr>
                <td colpan="6"><span asp-validation-for="ItemQuantity" class="text-danger"></span></td>
            </tr>
        </table>
    </form>
    <br />


    @section Scripts {
        <script nws-csp-add-nonce="true">

            $(document).ready(function () {
                alert('hello');
                console.log($('#MaterialCode'));
                $("#MaterialCode").val('');
                $("#MaterialDescription").val('');
                $("#ItemQuantity").val('');

            });

        </script>
    }


    Controller
    ---------------------------------
           [HttpPost]
            [ValidateAntiForgeryToken]
            [Authorize(Roles = UserRoles.ADMIN)]
            public ActionResult AddBOTItems(BOTItemEntryViewModel aBotItemVM, MaterialEntryViewModel materialEntry)
            {
                BOTDTO b = null;
                try
                {
                    b = _botRepository.FindExactDTO(aBotItemVM.ParentId);

                    if (ModelState.IsValid)
                    {
                        aBotItemVM.materialEntry = materialEntry;
                        _botRepository.AddBOTItem(aBotItemVM, base.currentUserDTO);

                        ViewBag.Message = "Record was saved.";
                    }

                    if (b == null)
                    {
                        RedirectToAction("Index");
                        throw new Exception("BOT is not found.");
                    }
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("BOT Add Item Error", e.Message);
                }

                aBotItemVM.materialEntry = null;
                aBotItemVM.materialEntry = new MaterialEntryViewModel();
                return AddBOTItems(b);
            }


            [HttpGet]
            [Authorize(Roles = UserRoles.ADMIN)]
            public ActionResult AddBOTItems(BOTDTO aBotDto)
            {
                if(aBotDto == null)
                {
                    throw new Exception("Add BOT Items:  aBotDto cannot be null");
                }

                populateBOTType();

                BOTEditViewModel botVM = new BOTEditViewModel();

                botVM.botdto = aBotDto;
                IEnumerable<BOTItemViewModel> itemList = _botRepository.GetBOTItems(aBotDto.BotNumber);

                botVM.BOTItemEntry = null;
                botVM.BOTItemEntry = new BOTItemEntryViewModel
                {
                    ParentId = aBotDto.BotNumber,
                    ItemQuantity = 0,
                    materialEntry = new MaterialEntryViewModel
                    {
                        MaterialCode = "",
                        MaterialDescription = ""
                    }
                };

                botVM.BOTItemList = itemList;

                return View("Edit", botVM);
            }

    Tuesday, August 4, 2020 10:28 PM

Answers

  • User1686398519 posted

    Hi tinac99,

    You didn't make it clear which input it is. I guess it is "<input asp-for="ItemQuantity" style="width:50px" />" based on the code you provided.

    1. "asp-for" is Tag Helpers, which is used in ASP.NET Core."HTML Helpers" is used in ASP.NET MVC.Below I give the correct code in ASP.NET MVC.
    2. You can use "ModelState.Clear();" to clear model fields.
    3. When you use "@section Scripts {}" it means you want to add something in a view which will be added in the Layout. Obviously "_BOTItemsEntryPartial" is a partial view, and you did not reference the Layout, so it will not be added successfully, and the jquery file (Usually it has been added in the Layout.)cannot be loaded, so the js code you write will report an error. You can view this in the browser through F12 .

    AddBOTItems

    @Html.Partial("_BOTItemsEntryPartial")

    _BOTItemsEntryPartial

    @using (Html.BeginForm("AddBOTItems", "Test4", FormMethod.Post))
    {
        @Html.TextBoxFor(m => m.ItemQuantity)
        <button type="submit" name="AddBOTItems" value="" class="btn btn-info">Add Item</button>
    }
    <script src="~/Scripts/jquery-3.4.1.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#ItemQuantity").val('');
        });
    </script>

    AddBOTItems

            public ActionResult AddBOTItems(BOTDTO aBotDto)
            {
               //The code here has not been modified, so it is omitted.
                ModelState.Clear();
                botVM.BOTItemEntry = new BOTItemEntryViewModel
                {
                    ParentId = aBotDto.BotNumber,
                    ItemQuantity = 0,
                    materialEntry = new MaterialEntryViewModel
                    {
                        MaterialCode = "",
                        MaterialDescription = ""
                    }
                };
             //The code here has not been modified, so it is omitted.
            }

    Here is the result.

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 5, 2020 10:04 AM

All replies

  • User1686398519 posted

    Hi tinac99,

    You didn't make it clear which input it is. I guess it is "<input asp-for="ItemQuantity" style="width:50px" />" based on the code you provided.

    1. "asp-for" is Tag Helpers, which is used in ASP.NET Core."HTML Helpers" is used in ASP.NET MVC.Below I give the correct code in ASP.NET MVC.
    2. You can use "ModelState.Clear();" to clear model fields.
    3. When you use "@section Scripts {}" it means you want to add something in a view which will be added in the Layout. Obviously "_BOTItemsEntryPartial" is a partial view, and you did not reference the Layout, so it will not be added successfully, and the jquery file (Usually it has been added in the Layout.)cannot be loaded, so the js code you write will report an error. You can view this in the browser through F12 .

    AddBOTItems

    @Html.Partial("_BOTItemsEntryPartial")

    _BOTItemsEntryPartial

    @using (Html.BeginForm("AddBOTItems", "Test4", FormMethod.Post))
    {
        @Html.TextBoxFor(m => m.ItemQuantity)
        <button type="submit" name="AddBOTItems" value="" class="btn btn-info">Add Item</button>
    }
    <script src="~/Scripts/jquery-3.4.1.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#ItemQuantity").val('');
        });
    </script>

    AddBOTItems

            public ActionResult AddBOTItems(BOTDTO aBotDto)
            {
               //The code here has not been modified, so it is omitted.
                ModelState.Clear();
                botVM.BOTItemEntry = new BOTItemEntryViewModel
                {
                    ParentId = aBotDto.BotNumber,
                    ItemQuantity = 0,
                    materialEntry = new MaterialEntryViewModel
                    {
                        MaterialCode = "",
                        MaterialDescription = ""
                    }
                };
             //The code here has not been modified, so it is omitted.
            }

    Here is the result.

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 5, 2020 10:04 AM
  • User-309523270 posted

    Thanks.  Works now.

    Wednesday, August 5, 2020 5:04 PM