操作返回局部视图和模型(Action returning Partial view and mode

2019-10-18 03:47发布

我是新来的MVC 3,我有关于正确的做法的问题。

想象一下,我有一个模型:

public class MyCustomModel
{
       [Required]
        public string UserName { get; set; }

        [Required]
        public DateTime? Birthdate { get; set; }

        [Required]
        public string City {get;set;} //To partial view

        [Required]
        public string Street {get;set;} //To partial view  
  }

在这里,我有一个观点

@ Html.TextBoxFor(M => m.UserName)@ Html.TextBoxFor(M => m.BirthDate)@ Html.Action( “LocationGroup”, “家庭”)//在此应城市和街道被渲染

我的局部视图将有somethign这样的:@ Html.TextBoxFor(M => m.City)@ Html.TextBoxFor(M => m.Street)

而这个控制器的作用:

    [ChildActionOnly]
    public ActionResult LocationGroup()
    {
        MyCustomModel model = new MyCustomModel (); //Should i really instantiate a new instace of the model??? and pass it to the partial view
        return PartialView("_TempView", model);
    }

基本上我总的看法将所有与texboxex领域,但现在在我的部分观点我也想有几个从我的模型这些化子性质的正确呈现和submiting形式应为同一型号所有其他属性可用后。

所以我的问题,其中发送局部视图后面的动作,我应该真的实例化模型的新instace? 但随后的数据将在模型的两个实例之间拆分没有?

如何安排一下,我怎么能那么数据屁股从局部视图的一般看法模式?

Answer 1:

我没有得到你的问题,但你可以注释与ActionResults HttpGetHttpPost具有相同的名称(但不同的签名,因为他们的方法毕竟)一样

 [HttpGet]
 [ChildActionOnly]
    public ActionResult LocationGroup()
    {
        Model model = new Model();
        return PartialView("_TempView", model);
    }

在视图中,你必须做一些像

@model YOURMODELNAME
@using(Html.BeginForm("LocationGroup","Controller",FormMethod.POST)){
 @Html.TextBoxFor(x=>x.UserName)
 @Html.TextBoxFor(x=>x.Birthdate )
 <input type="submit" value="submit" />
}

现在定义后类型的ActionResult

 [HttpPost]
 [ChildActionOnly]
public ActionResult LocationGroup(YOUR_MODEL_TYPE model)
{
    if(ModelState.IsValid){
     //do something
    }
}

默认的模型绑定将调查的HttpContext并模型的属性值公布名称之间的匹配,并自动绑定值



文章来源: Action returning Partial view and model