Save value in ASP.NET MVC5 variable

0

I need to save IDs that pass through the url

  

link

I need to capture that "1009" value and take it to a

<input name="codigo" type="text"class="form-control" value="AQUI
 NECESITO QUE ESTE ESE VALOR DE LA URL"/>

I need to save that value in a variable.

My sight

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>tb_familiares</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.nombres, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.nombres, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.nombres, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.documento_identidad, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.documento_identidad, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.documento_identidad, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.fecha_nacimiento, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.fecha_nacimiento, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.fecha_nacimiento, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.sexo, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.sexo, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.sexo, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.parentesco, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.parentesco, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.parentesco, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.celular, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.celular, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.celular, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.telefono, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.telefono, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.telefono, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.cod_colaborador, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">

// HERE IS WHERE I WANT THAT INPUT WITH THAT ID //

                @Html.EditorFor(model => model.cod_colaborador, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.cod_colaborador, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>

My controller

namespace WebApplicationSIOldMutual.Controllers
{
    public class familiaresController : Controller
    {
        private sioldmutualEntities db = new sioldmutualEntities();

        // GET: familiares
        public ActionResult Index()
        {
            return View(db.tb_familiares.ToList());
        }

        // GET: familiares/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            tb_familiares tb_familiares = db.tb_familiares.Find(id);
            if (tb_familiares == null)
            {
                return HttpNotFound();
            }
            return View(tb_familiares);
        }

        // GET: familiares/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: familiares/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "id_familiar,nombres,documento_identidad,fecha_nacimiento,sexo,parentesco,celular,telefono,cod_colaborador")] tb_familiares tb_familiares)
        {
            if (ModelState.IsValid)
            {
                db.tb_familiares.Add(tb_familiares);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(tb_familiares);
        }

        // GET: familiares/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            tb_familiares tb_familiares = db.tb_familiares.Find(id);
            if (tb_familiares == null)
            {
                return HttpNotFound();
            }
            return View(tb_familiares);
        }

        // POST: familiares/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "id_familiar,nombres,documento_identidad,fecha_nacimiento,sexo,parentesco,celular,telefono,cod_colaborador")] tb_familiares tb_familiares)
        {
            if (ModelState.IsValid)
            {
                db.Entry(tb_familiares).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(tb_familiares);
        }

        // GET: familiares/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            tb_familiares tb_familiares = db.tb_familiares.Find(id);
            if (tb_familiares == null)
            {
                return HttpNotFound();
            }
            return View(tb_familiares);
        }

        // POST: familiares/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            tb_familiares tb_familiares = db.tb_familiares.Find(id);
            db.tb_familiares.Remove(tb_familiares);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

My route file

namespace WebApplicationSIOldMutual
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

I'm pretty new at asp.net mvc5.

    
asked by ByGroxD 28.03.2017 в 17:11
source

2 answers

2

First of all I advise you to study the concept of the MVC more.

The way MVC to do what you indicate is as follows:

  • Create a model that contains the information you will need in the view:

    public class MiModelo
    {
        public int ID { get; set; }
        ...
        /* Puedes establecer un constructor para el modelo que tome los
           parámetros que quieras: */
    
        public MiModelo(int id)
        {
             this.ID = id;
        }
    }
    
  • In the controller create an action ( ActionResult ) that expects that parameter that you will send and send the model to the view:

    public ActionResult Index(int id)
    {
        return View(new Models.MiModelo(id));
    }
    
  • In the view you consume the Model that you passed through the controller; The first step is to declare it:

    // Asumiendo que lo haces con el motor Razor
    @model MiProyecto.Models.MiModelo
    @{
        ViewBag.Title = "- Index";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    ...
    

    and place the model property where you want within the view:

    <input name="codigo" type="text"class="form-control" value="@Model.ID"/>
    
  • As I told you at the beginning, you need to document more about the MVC concept, I leave you a small tutorial and here another to start. Greetings!

    EDIT

    Starting from the clarification that you do, the only thing you need is to receive that parameter id in the action Create , in the rest it is the same, except that you can have an empty constructor for the model:

    public class tb_familiares
    {
        public int ID { get; set; }
        ...
        public tb_familiares() { }
    }
    

    and in your controller assign the value of that ID:

    public ActionResult Create(int id)
    {
        return View(new tb_familiares() { ID = id });
    }
    

    and in the view:

    <div class="form-group">
        @Html.LabelFor(model => model.ID, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
            @Html.EditorFor(model => model.ID, new { htmlAttributes = new { @class = "form-control disabled" } }) <!-- Nota el "disabled" -->
        </div>
    </div>
    
        
    answered by 28.03.2017 / 17:25
    source
    2

    Without using a model

    In your RouteConfig.cs there you define the url friendly, that is:

    you want to access http://localhost:50210/familiares/Index/1009 you must have a route configured in this way:

    routes.MapRoute(
        name: "Familiares",
        url: "Familiares/Index/{id}",
        defaults: new { controller = "Familiares", action = "Index", id = UrlParameter.Optional }
    ); 
    
      

    id = UrlParameter.Optional indicates that the id will not always be necessary,   if what you want is to be necessary just remove the aforementioned.

         

    In the RouteConfig.cs there is a default route that would likewise serve you and it would not be necessary to add this one that I mention to you

    in your controller you should have something like this:

    public ActionResult Index(int id){
        ViewBag.id = id;//guardando el valor de 1009
        return View()
    }
    

    In your sight.

    <input name="codigo" type="text"class="form-control" value="@ViewBag.id"/>
    

    Using a model

    having the following model:

    public class ModeloUrl{
        public int id {get; set;}
    }
    

    in the controller would look like this:

    @using Proyect1.Models;
    
    public ActionResult Index(int id){
        ModeloUrl model = new ModeloUrl();
        model.id = id;
        return View(model)
    }
    

    in the view you would have something like this:

    @model Proyect1.Models.ModeloUrl
    ...
    <input name="codigo" type="text"class="form-control" value="@Model.id"/>
    ...
    
      

    I leave you a workshop that the good friend did @Fredyfx on ASP.net MVC from scratch, I hope you be useful: link + source code on Github link

        
    answered by 28.03.2017 в 17:23