How do I send the focus to an input tag from the actionresult of a controller?

1

I'm starting in C # and MVC, I've already done some things in VBA, and I was thinking about translating this into ASP.net MVC5 but I've encountered the problem that before, in the form I had some textbox and to send the focus to one of them when an error occurred, just put textbox.setfocus, but to be another language and have other ways to communicate with the user interface, I do not know how to send the focus to a "textbox" in the view (razor).

I have tried with form["Campo"].algo(); but I have not had any result that is not an error and on the web I only find confusing things and sending focus from the load of the view, but I also get an error when trying one or the other.

Have some idea of how you could send the focus to the field in the view, say:

public actionresult accionDeVista(Formcollection form)
{if(x>0)
{form["campo"].setfocus();
}
else
{
form["campo2"].setfocus();
}
return view();
}

Something like that.

    
asked by snithfferx 22.08.2017 в 08:19
source

1 answer

0

You could use ViewBag to store from the controller what control you want the focus to have and then, using javascript, apply the focus on that element. It would be something like this:

Driver

public ActionResult accionDeVista(Formcollection form)
{
    if(x>0)
    {
        ViewBag.FocoEn = "campo";
    }
    else
    {
        ViewBag.FocoEn = "campo2";
    }
    return View();
}

Vista

<input type="text" id="campo" />
<input type="text" id="campo2" />

@if(!string.IsNullOrEmpty(ViewBag.FocoEn) {
    <script type="text/javascript">

        //con javascript puro
        document.getElementById('@ViewBag.FocoEn').focus();

        //o si tienes jQuery
        $('#@Viewbag.FocoEn').focus();
    </script>
}

It's very schematic, but you can get a rough idea

    
answered by 26.09.2017 в 15:21