简体   繁体   中英

Passing ViewModel to Web API controller

Let's say I have two projects in my solution. One is for the front-end. Another one is the back-end. In my front-end project which is built using MVC Web Application, I have this ViewModel. How does my back-end project which is the Web API controller know this ViewModel? Previously with only one project for both front-end and back-end, my code is as below.

public class ChangePinForm
{
    [Range(100000, 999999), Display(Name = "Enter Current Card Pin")]
    [DataType(DataType.Password)]
    public int OldCardPin { get; set; }

    [Range(100000, 999999), Display(Name = "Enter New Card Pin")]
    [DataType(DataType.Password)]
    public int NewCardPin { get; set; }

    [Range(100000, 999999), Display(Name = "Enter New Card Pin Again")]
    [DataType(DataType.Password)]
    public int ConfirmNewCardPin { get; set; }
}

    [HttpPost]
    public ActionResult ChangePin(ChangePinForm changePinForm)
    {
        selectedBankAccount = db.BankAccounts.Find(Session["userid"]);
        if (changePinForm.OldCardPin != selectedBankAccount.PinCode)
        {
            ViewBag.Error = "Please key in the correct current pin number.";
            return View();
        } else if (changePinForm.NewCardPin != changePinForm.ConfirmNewCardPin)
        {
            ViewBag.Error = "New card pin number and Confirm new card pin number do not match.";
            return View();
        } else
        {
            selectedBankAccount.PinCode = changePinForm.ConfirmNewCardPin;
            db.SaveChanges();
            return View("Done");
        }

    }

You can simply receive the object in your API in the back-end, something like

[HttpPost("changepin")]
public ActionResult ChangePin([FromBody] ChangePinForm changePinForm)

This is going to reference ChangePinForm from a separate library (i suggest to use .net standard 2.0) so you can both reference from .net core and .net framework

As Sri Harsha said, you should have your viewmodel class in both solutions.

Alternative, to reduce duplication, you could have a separate class library solely for your model definitions, and reference this class in both projects.

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