简体   繁体   中英

Model not updated from view to controller

I'm trying to do that:

  1. Create a Model, add it on a session and send it to the view.
  2. Change Model fields on my view
  3. Get the Model from session updated on my controller

The problem is that my model is never updated when I'm changing values on textboxes, I'm sure that I'm missing something with razor, View:

@model MvcTestApp.Models.Car

<div class="b1">

    <div class="b2">@Html.EditorFor(e => e.KM)</div>                    
    <div class="b2">@Html.EditorFor(e => e.RegistrationNumber)</div>

</div>

@Html.ActionLink("Car", "sendCar")

Controller: On SendCar, I would like to get the model updated.

namespace MvcTestApp.Controllers
{
    public class CarController : Controller
    {
        public ActionResult Show()
        {
            var model = new MvcTestApp.Models.Car()
            {
                RegistrationNumber ="12345",
                KM = "12345"
            };

            Session["temp"] = model;
            return View("Show",Session["temp"]);
        }


        public ActionResult sendCar()
        {
           return View("Show", Session["temp"]);
        }       

    }
}

Model:

namespace MvcTestApp.Models
{

    public class Car
    {

        [DataType(DataType.Text)]
        public string KM { get; set;}

        [DataType(DataType.Text)]
        public string RegistrationNumber { get; set;}

    }  
}

You need to make your sendCar controller to update the model. Currently, all the changes you do will only persist locally until you navigate away from the page. You need to post the changed model back to the server.

Take a look at the "Handling edits" part of this example to see how it can be done:

Asp.net tutorials

You should read a beginner tutorial about ASP.NET MVC, which will explain you how to send data from a form to a controller, as it seems you are absolutely not aware of how to do this.

You are not missing 'something', you are missing all about sending data from forms to controllers.

The way to do this is by wrapping your model details in a form with a submit function. Then in your sendCar method take in a Car object and the model binding will take care of setting everything on the new object.

If you're wanting to persist this (I assume this is just for testing purposes?) then perhaps make your car that you're returning in your show method a class variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM