Juan José Juan José - 4 days ago 6
C# Question

Populate an input text with the incoming URL parameter with MVC

I have a link in one view that when i clicked it goes to another view passing an id parameter into the URL like this:

<a href=Gestion/ImagenesPublicacion?id=2 class="alert-link">Publicar imagen</a>


That URL is calling this method action of the controller:

[Authorize]
public ActionResult ImagenesPublicacion(int id)
{
return View();
}


This action method it is rendering the HTML of this view that has an input text that i want to populate with the id parameter:

<div class="col-lg-6">
<p><strong>Nº Expediente:</strong></p>
<input class="form-control" id="ExpedienteNro" name="ExpedienteNro" type="number" placeholder="Nº Expediente" required autocomplete="off">
</div>


Any possible ideas of how can i do this?

Answer

If you are absolutely sure you only need the one value, you can set it as entire model.

public ActionResult Index(int id = 0)
{
    return View(id);
}

and the view

@model int

<div class="col-lg-6">
    <p><strong>Nº Expediente:</strong></p>
    @Html.TextBox("NoExpediente", Model, new { @class = "form-control",
        @type = "number", placeholder = "Nº Expediente", 
        autocomplete = "off" })    
</div>

Although as the comments suggest you may well prefer to use a model. In particular if you want to post the page back to the server, you stand a much greater risk of typos compared to the strongly typed @Html.TextBoxFor() method or just populating the value from the ViewBag.

Comments