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

问题描述 投票:0回答:1

我有一个表格:剃刀视图:

@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生成名为='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);
}

UserViewModel:

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]之类的东西访问它们,但显然这不起作用。

我是否以正确的方式解决这个问题?如果有的话,是否有人对此如何运作有任何建议?

jquery asp.net-mvc model-binding
1个回答
1
投票

由于你有多个<input>元素具有相同的name="Mac"属性(一个用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);
}
© www.soinside.com 2019 - 2024. All rights reserved.