gpt4 book ai didi

c# - 模型未绑定(bind)到将 Null 作为值传递的 Action

转载 作者:行者123 更新时间:2023-11-30 22:21:17 25 4
gpt4 key购买 nike

我不知道为什么,模型没有绑定(bind)到创建操作:

View 模型:

public class AddressContactViewModel
{
// Primary properties
public int Id { get; set; }
public string Contact { get; set; }

// Navigation properties

[Display(ResourceType = typeof(HeelpResources), Name = "AddressContactViewModelNameLabel")]
[Required(ErrorMessageResourceName = "ErrorMsgRequiredField", ErrorMessageResourceType = typeof(HeelpResources))]
public int ContactType_Id { get; set; }

public int Address_Id { get; set; }

// ViewModel dropdownlists
public IEnumerable<SelectListItem> ContactTypeList { get; set; }
}

查看:

@model Heelp.ViewModels.AddressContactViewModel

@using (Html.BeginForm()) {

@Html.AntiForgeryToken()

@Html.HiddenFor(m => m.Address_Id)

<fieldset>
<legend>AddressContactViewModel</legend>

<div id="year">
@Html.DisplayNameFor(m => m.ContactType_Id)
@Html.DropDownListFor(m => m.ContactType_Id, Model.ContactTypeList, HeelpResources.AddressContactViewModelContactTypesListDropDownFirstRecord)
@Html.ValidationMessageFor(m => m.ContactType_Id)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.Contact)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.Contact)
@Html.ValidationMessageFor(m => m.Contact)
</div>

<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}

行动帖:

    [HttpPost]
[ValidateAntiForgeryToken]
public virtual ActionResult ContactCreate(AddressContactViewModel contact)
{
var contactDto = Mapper.Map<AddressContactViewModel, AddressContactDto>(contact);

_addressContactService.Create(contactDto);

return RedirectToAction(MVC.Address.ContactList());
}

编辑:获取:

    public virtual ActionResult ContactCreate(int addressId)
{
var model = new AddressContactViewModel
{
Address_Id = addressId,
ContactTypeList = ContactTypeDropDownList()
};

return View(model);
}

当我提交表单时,我在 ContactCreate 操作的联系人参数中收到“null”,这是为什么?

谢谢

最佳答案

难以置信,我发现了问题所在,操作的参数与 ViewModel 中的字段同名,更改参数名称后一切正常发现:

    [HttpPost]
[ValidateAntiForgeryToken]
public virtual ActionResult ContactCreate(AddressContactViewModel addressContact) // HERE I CHANGE FROM contact TO addressContact AND THE PROBLEM GET SOLVED
{
var contactDto = Mapper.Map<AddressContactViewModel, AddressContactDto>(addressContact);

_addressContactService.Create(contactDto);

return RedirectToAction(MVC.Address.ContactList(addressContact.Address_Id));
}

关于c# - 模型未绑定(bind)到将 Null 作为值传递的 Action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14480243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com