본문 바로가기
.Net

MVC - submit change or clear value of Textbox what else

by 올엠 2020. 10. 28.
반응형

During a recent operation, we will send the value of Textbox to Get via submit, and then we will try to remove the value entered in Textbox, but we will share the method we found when ViewBag is not working.

In MVC, there are times when you need to exchange a lot of data with a View.
In particular, you may need to pass a value after submit, or delete the value you entered before submit.
Normally, you can use ViewBag and ViewData.
ViewBag and ViewData can be used without difficulty.

 

However, there is a case where the existing input value does not disappear. ModelState.Clear () is a function that can be used in this case.

ModelState is a property of a Controller, and can be accessed from those classes inherit from System.Web.Mvc.Controller.

https://docs.microsoft.com/ko-kr/dotnet/api/system.web.mvc.controller.modelstate?view=aspnet-mvc-5.2

 

Controller.ModelState Property (System.Web.Mvc)

Gets the model state dictionary object that contains the state of the model and of model-binding validation.

docs.microsoft.com

How to use ModelState

When ModelState is initialized, the current value and error value will be initialized.
This can be used to initialize input values
You can use the ViewBag and ViewData to pass the values ​​you want to pass.

public ActionResult Index()
{
    ModelState.Clear();
    ViewBag.CurrentGroup = [Your want value here];
    return View()
}

If you enter ModelState.Clear (); in the controller, the value and the name object will disappear.
After that, you can set the value to be transmitted newly by using ViewBag, etc., and initialize the value of TextBox.

The settings on the View page can be applied as follows:

                <td>
                    @Html.TextBox("Group", ViewBag.CurrentGroup as string, new { placeholder = "input group" })
                </td>

When set as above, the input value does not enter if ViewBag does not have a value, and if there is a value, the entered value is entered.

If you want to reset, ModelState.Clear(); will remove all previously entered values.

반응형