如何在 ASP.NET MVC 中保存具有相同名称属性的多个数据?

How to save multiple data with same name attribute in ASP.NET MVC?

我有一个表格: Razor 视图:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group row">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "col-sm-2 col-md-1 col-form-label" })
        <div class="col-sm-10 col-md-3">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group row">
        @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "col-sm-2 col-md-1 col-form-label" })
        <div class="col-sm-10 col-md-3">
            @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group row">
        @Html.LabelFor(model => model.Mac, htmlAttributes: new { @class = "col-sm-2 col-md-1 col-form-label" })
        <div class="col-sm-10 col-md-3">
            <span class="add-new-icon glyphicon glyphicon-plus-sign" id="add_mac"> </span>
            @Html.EditorFor(model => model.Mac, new { htmlAttributes = new { @class = "form-control", @id = "mac_addr" } })

            @* @Html.DropDownListFor(x => Model.SelectedMac, new SelectList(ViewBag.Macs, "Value", "Text"), htmlAttributes: new { @class = "form-control", id = "mac_addr" })
        @Html.ValidationMessageFor(x => x.SelectedMac, "", new { @class = "text-danger" }) *@

        </div>
    </div>
}

渲染HTML:

<div class="form-group row new_mac_wrapper">
    <div class="col-md-offset-3">
        <div class="new_mac_container">
        </div>
    </div>
</div>

<div class="form-group row">
    <div class="col-md-offset-2 col-sm-10 col-md-2">
        <input type="submit" value="Register" class="btn btn-primary col-sm-offset-1" />
    </div>
</div>
}

<form action="/Users/Register" method="post">
   <input name="__RequestVerificationToken" type="hidden" value="w3GWVNW8nPHGcTz1kIBbyGu7386qDwfOFNprYBlmF8ve9KzKS47SyVOYFgf_jGFRzOum7oNKUZRKqtIinDP-ed8Lt5kP7kqHFJzrLmgG9P81">    
   <div class="form-group row">
      <label class="col-sm-2 col-md-1 col-form-label" for="Name">Name</label>
      <div class="col-sm-10 col-md-3">
         <input class="form-control text-box single-line" id="Name" name="Name" type="text" value="">
         <span class="field-validation-valid text-danger" data-valmsg-for="Name" data-valmsg-replace="true"></span>
      </div>
   </div>
   <div class="form-group row">
      <label class="col-sm-2 col-md-1 col-form-label" for="Email">Email</label>
      <div class="col-sm-10 col-md-3">
         <input class="form-control text-box single-line" id="Email" name="Email" type="text" value="">
         <span class="field-validation-valid text-danger" data-valmsg-for="Email" data-valmsg-replace="true"></span>
      </div>
   </div>
   <div class="form-group row">
      <label class="col-sm-2 col-md-1 col-form-label" for="Mac">Mac</label>
      <div class="col-sm-10 col-md-3">
         <span class="add-new-icon glyphicon glyphicon-plus-sign" id="add_mac"> </span>
         <input class="form-control text-box single-line" id="mac_addr" name="Mac" type="text" value="">
      </div>
   </div>
   <div class="form-group row new_mac_wrapper">
      <div class="col-md-offset-3">
         <div class="new_mac_container">
            <div class="col-sm-10 col-md-3 positioned_relative margin-bottom">
               <input readonly="" name="Mac" type="text" class="form-control" value="12556564">
               <span class="remove_mac remove-icon glyphicon glyphicon-minus-sign"> </span>
            </div>
            <div class="col-sm-10 col-md-3 positioned_relative margin-bottom">
               <input readonly="" name="Mac" type="text" class="form-control" value="444444">
               <span class="remove_mac remove-icon glyphicon glyphicon-minus-sign"> </span>
            </div>
         </div>
      </div>
   </div>
   <div class="form-group row">
      <div class="col-md-offset-2 col-sm-10 col-md-2">
         <input type="submit" value="Register" class="btn btn-primary col-sm-offset-1">
      </div>
   </div>
</form>

这里我有三个具有相同名称属性的输入'Mac'。使用 jquery:

生成具有 name='Mac' 的附加输入
$(document).ready(function(){
    $('#add_mac').on('click', function(){
        var mac = $('#mac_addr').val();
        if(!mac){
          alert('Input MAC ADRESS First');
          return;
        }
        var newMAChtml  = '<div class="col-sm-10 col-md-3 positioned_relative margin-bottom">';
            newMAChtml += '<input readonly name="Mac" type="text" class="form-control" value="'+mac+'" >';
            newMAChtml += '<span class="remove_mac remove-icon glyphicon glyphicon-minus-sign"> </span>';
            newMAChtml += '</div>';
            $('.new_mac_container').append(newMAChtml);
            $('#mac_addr').val('');
    });

    $('body').on('click', '.remove_mac', function() {
          $(this).closest('div').remove();
    });
});

我想保存这三个输入。我正在尝试如下:

[HttpPost]
public ActionResult Register(UserViewModel model)
{
    CancellationTokenSource cancelToken = new CancellationTokenSource();

    AccountRegistrationRequestMessage requerstMessage = new AccountRegistrationRequestMessage();
    requerstMessage.FullName = model.Name; 
    requerstMessage.EmailAddress = model.Email; 
    requerstMessage.MacAddresses.Add(model.Mac);

    requerstMessage.RegistrationType = AccountRegistrationEnum.IndividualAccountRegistration;

    Task<AccountRegistrationResponseMessage> response = _interactor.Handle(requerstMessage, cancelToken.Token);

    UserViewModel viewModel = _presenter.Handle(response.Result, model, ModelState);

    if (response.Result.ValidationResult.IsValid)
    {
        //return View("DetailView", viewModel);
    }
    return View(viewModel);
}

用户视图模型:

public class UserViewModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string Mac { get; set; }
}

但目前只保存了 <input name="Mac" ... 的最后一个值。我想过使用 for 循环,然后通过 form["Mac"][i] 之类的方式访问它们,但显然这是行不通的。

我的处理方式是否正确?如果是,有人对此有何建议?

由于您有多个具有相同 name="Mac" 属性的 <input> 元素(一个具有 EditorFor 并且其他是动态生成的),首先您应该更改 属性 类型Mac:

public string Mac { get; set; }

给这个:

public List<string> Mac { get; set; }

模型绑定器会将文本框中的值视为字符串集合,并根据 POST 请求将它们绑定在一起。之后,您可以使用 AddRange:

检索 MAC 个地址列表
[HttpPost]
public ActionResult Register(UserViewModel model)
{
    CancellationTokenSource cancelToken = new CancellationTokenSource();

    AccountRegistrationRequestMessage requerstMessage = new AccountRegistrationRequestMessage();
    requerstMessage.FullName = model.Name; 
    requerstMessage.EmailAddress = model.Email; 

    // Use ForEach() method to add IEnumerable collection into ICollection
    // requerstMessage.MacAddresses.AddRange(model.Mac); 
    model.Mac.ForEach(x => requerstMessage.MacAddresses.Add(x));

    // other stuff

    UserViewModel viewModel = _presenter.Handle(response.Result, model, ModelState);

    if (response.Result.ValidationResult.IsValid)
    {
        //return View("DetailView", viewModel);
    }

    return View(viewModel);
}