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

后端 未结 5 1364
旧时难觅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 16:13

    My question is can I post data to NewModel from my form? 
    

    The short answer is yes you can post the form to any controller action on any controller related to any Model in your application.

    For example, for your form to post to the "Add" action on the NewModel controller:

    @using (Html.BeginForm("Add", "NewModel"))
        {
            @Html.Hidden("ID", "1")
            @Html.Hidden("UserID", "44")
            @Html.TextArea("Description")
        }
    

    Since your view is strongly typed to your Car model, You can either change this and send a ViewModel to your view whose type matches the model your updating (as Darin demonstrated), or you'll need to map the post data from Car onto NewModel in your controller:

    On the CarController's Add action (Post) :

    [HttpPost]
    public PartialViewResult Add(Car model)
    {
        //now map attribute values from the Car model onto 
        //corresponding attributes of an instance of NewModel
        NewModel new = new NewModel();
        new.ID = model.ID;
        new.UserID = model.UserID;
        new.Desc = model.Description;
        //etc...
    
        //update your model/db
        _db.Add(new);
    
        //Redirect however you wish...
    }
    

    Also, check out AutoMapper, an object-to-object mapper which automates mapping of ViewModels onto Models and vice versa.

提交回复
热议问题