Posting to another model from a form in ASP.NET MVC

后端 未结 5 1363
旧时难觅i
旧时难觅i 2021-02-13 15:44

If I have a view that has a model, lets say Car..

@model Project.Car

inside that view I want to create a form that sends data to a new model

5条回答
  •  梦如初夏
    2021-02-13 15:56

    You have a discrepancy between the name of your model and your action. In the example you have shown the model is called Add whereas in your action you are using ViewModels.NewModel. Even worse, your view is strongly typed to a model called Car. Messy all this.

    So start by defining a correct view model:

    public class CarViewModel
    {
        public int ID { get; set; }
        public int UserID { get; set; }
        public string Description { get; set; }
    }
    

    and then a controller:

    public class CarsController: Controller
    {
        public ActionResult Add()
        {
            var model = new CarViewModel
            {
                // don't ask me, those are the values you hardcoded in your view
                ID = 1,
                UserID = 44,
            };
            return View(model);
        }   
    
        [HttpPost]
        public PartialViewResult Add(CarViewModel model)
        {
            ...
        }
    }
    

    and a corresponding strongly typed view to your view model:

    @model CarViewModel
    @using (Html.BeginForm())
    {
        @Html.HiddenFor(x => x.ID)
        @Html.HiddenFor(x => x.UserID)
        @Html.TextAreaFor(x => x.Description)
        
    }
    

提交回复
热议问题