'How to combine two html form input tag's value and store it into model object of C#

This is my html form

@model Demo.Models.ContactU

<form asp-action="Create">
    <div class="col-md-6 col-12 bottom-margin-5">
        <input type="text" class="form-control" placeholder="First name" aria-label="First name">
    </div>
    <div class="col-md-6 col-12 bottom-margin-5">
        <input type="text" class="form-control" placeholder="Last name" aria-label="Last name">
    </div>
</form>

And this is my model

public partial class ContactU
{
    public string Name { get; set; }
}

I want to Combine First name and Last name into whole name and store it into my database

Controller method

[HttpPost]
public IActionResult Contact(ContactU contactU)
{
    _dbContext.ContactUs.Add(contactU);
    return RedirectToAction("Index");
}


Solution 1:[1]

You have to add name attributes to your inputs: name="firstName" and name="lastName". Than you should add FirstName and LastName properties to your model. And if you want to access those as a single property, you can use get only property:

public class Contact
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string FullName => $"{FirstName} {LastName}";
}

What you want to do(map two inputs into single property) is also possible, but you will have to write custom ModelBinder, but it will be more complex and not sure if you want to go into that direction.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Uriil