how to write code for html controls in MVC RRS feed

  • Question

  • User-1651858287 posted

    I have a checkbox 

    <label for="ChFileOne">
        File One
        <input type="checkbox" name="ChFileOne" id="ChFileOne">

    I want to check it, if a file exists.

    in web forms which I am familiar with, I would use the code behind.


        chFileOne.checked = true;

    am trying to learn MVC I want to know how to write a similar statement.


    Friday, May 22, 2020 6:19 PM

All replies

  • User-474980206 posted

    Mvc is a template engine, not a component model. You just set bool value in the view model, say FileOneExists, then bind to it


    In the action code, you set the value true or false.

      Model.FileOneExits = ifFileExists();

    The way to think about the MVC pattern is that there is a UI view engine you send messages to (model) and it updates the UI (produces html in web apps). A UI operation sends a message to the controller (form post or navigation), the controller code does what is required to process the message (action parameters) and builds a new view model and calls the view engine to update the UI.

    the view should only have logic to properly render the view.it should not have logic like does file exists, only how to render the fact.

    Friday, May 22, 2020 6:27 PM
  • User475983607 posted

    In MVC you get to write what ever HTML you like right in the View using Razor syntax.   The following example is contrived but should illustrate how easy it is to render HTML in MVC.   Normality, a model and HTML helpers are used in MVC.  

        <label for="ChFileOne">
            File One
            <input type="checkbox" name="ChFileOne" id="ChFileOne" @ViewBag.Checked>
        public class GeneralController : Controller
            // GET: General
            public ActionResult Index()
                ViewBag.Checked = "checked";
                return View();

    There are many examples of how to use check boxes in MVC that you can find with a Google search.


    Friday, May 22, 2020 6:39 PM
  • User1686398519 posted

    Hi,  sweetSteal

    According to your needs, I made an example, please refer to it.

    Remarks: TempData is used to pass data from one request to the next request.


    @using (Html.BeginForm("CheckBoxTests", "Home"))
    <input type="checkbox" name="test" checked="@TempData["ischecked"]" />
    <button type="submit">submit</button>


     public ActionResult Index()
    return View();
    public ActionResult CheckBoxTests()
    if (true)
    TempData["ischecked"] = "checked";
    return View("Index");

    Here is the result.

    Best Regards,


    Tuesday, May 26, 2020 2:56 AM