简体   繁体   中英

Two the same models in one view MVC

I am having one form in my website. The form contains information about two localizations. First localization called FROM and second called TO. In my view I am using

@model DDP.Models.Localization

Here is my Localization entity:

public class Localization
{
    [Key]
    public int ID { get; set; }
    [Required]
    public string Province { get; set; }
    [Required]
    public string City { get; set; }
    [Required]
    public string PostalCode { get; set; }

    public string StreetAdres { get; set; }
}

The problem is I want pass to my controller two instances of Localization like below:

public ActionResult AddRoute(Localization from, Localization to)
{
    return View();
}

There is problem when I want to do it like below because I have two the same models.

@Html.TextBoxFor(model => model.City, new { @id = "cityFrom", @class = "form-control", @placeholder = "Miasto", @style = "margin-bottom: 10px;" })

Can somone show me right direction? Thanks!

Make a viewModel hosting the two instances, and use that into your view.

namespace DDP.ViewModels
{
    public class vm
    {
        Localization L1 {get; set;}
        Localization L2 {get; set;}
    }
}

and use it into your view like this:

public ActionResult AddRoute(Localization from, Localization to)
    {
        DDP.ViewModels.vm ret = new DDP.ViewModels.vm() { L1 = from, L2 = to};
        return View(ret);
    }


@model DDP.ViewModels.vm

@Html.TextBoxFor(model => model.L1.City, new { @id = "cityFrom", @class = "form-control", @placeholder = "Miasto", @style = "margin-bottom: 10px;" })

(I didn't actually test the code, I just typed it here into the editor maybe there's some mistake but hopefully it should put you onto the right way!)

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