gpt4 book ai didi

asp.net-mvc-3 - 发回 View 后值不会改变?

转载 作者:行者123 更新时间:2023-12-02 08:51:59 25 4
gpt4 key购买 nike

编辑:我更改了我的问题和代码以更好地阐明我的问题

我有这个(强类型 View )确实使用 Controller 中为该特定模型提供的值

我想从另一个模型向模型添加一些东西,从我的 httpPost 操作回发后没有任何反应......

提前致谢!

------------------------------------其他代码来进一步澄清我的问题----

 public class Address
{
public int Id { get; set;}
public String Name { get; set;}
}

public class OtherAddress
{
public int Id { get; set;}
public String Name { get; set;}
public String City { get; set;}
}

public class MasterModel
{
public Address Address { get; set;}
public List<OtherAddress> OtherAddressess { get; set;}
}



public ActionResult Create()
{
MasterModel Model = new MasterModel();
Model.Person = new Person();
Model.Address = new Address();
Model.OtherAdressess = new List<OtherAddress>();

DBContext _db = new DBContext();
Model.OtherAdressess = _db.OtherAddressess.Where(a=> a.City == "Amsterdam");
return View(Model);
}

在 View 中

    @model Project.Models.MasterModel

List<SelectListItems> items = new List<SelectListItems>();

foreach(var a in Model.OtherAddressess)
{
SelectListItem item = new SelectListItem();
item.Value = a.Id.toString();
item.Text = a.Street;
}

@using (@Html.BeginForm())
{
<div>
<select name="otheraddress">
foreach(var i in Items)
{
<option value=@i.Value>@i.Text</option>
}
</select>
<input type="submit" name="select" value="Select Address"/>
</div>
<div>
@Html.EditorFor(model => Model.Address.Name)
<div>
<p>
<input type="submit" value="Submit"/>
</p>
}

在帖子中

    [HttpPost]
public ActionResult Create(MasterModel Model)
{
String otherAddressSelected = Request.Params["select"];
if(!String.IsNullOrEmpty(otherAddressSelected))
{
int id = int.Parse(Request.Params["otheraddress"]);
DBContext _db = new DBContext();
OtherAddress oa = _db.OtherAddress.Single(oa=> oa.Id == id);
Model.Address.Name = oa.Name;
return View(Model);
}
//other stuff here
}

最佳答案

如果您想在 [HttpPost] Controller 中更改模型的值,您必须删除要更改的实例/属性的模型状态。例如:

  [HttpPost]
public ActionResult Index(SomeModel model)
{
ModelState.Remove("Name");
model.Name = "some new name";
return View(model);
}

this得到答案例子

关于asp.net-mvc-3 - 发回 View 后值不会改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7818414/

25 4 0