Action returning Partial view and model

橙三吉。 提交于 2019-12-13 19:37:45

问题


I'm new to MVC 3 and I have a question regarding the correct approach.

Imagine I have a model:

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  
  }

And here I have a view

@Html.TextBoxFor(m => m.UserName) @Html.TextBoxFor(m => m.BirthDate) @Html.Action("LocationGroup", "Home") //In this should the city and street be rendered

My Partial View will have somethign like that: @Html.TextBoxFor(m => m.City) @Html.TextBoxFor(m => m.Street)

And this the action in the controller:

    [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);
    }

Basically my general view will have all the field with texboxex, but now in my partial view i also would like to have few of those propeties from my model be rendered correctly and after submiting the form should be available in the same model as all other properties.

So my question, in the action which send the partial view back, should i really instantiate a new instace of the model? But then the data will be split between 2 instances of the model no?

How to arrange that, how can i then ass the data to the general views model from partial view?


回答1:


i didnt get your question but you can annotate the ActionResults with HttpGet and HttpPost having same names (but different signatures, because they are methods after all) like

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

in the view you must be doing something like

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

now define a post type ActionResult

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

the default model binder will look into the HttpContext for the match between the posted value names and the properties of your model and bind the value automatically



来源:https://stackoverflow.com/questions/16656073/action-returning-partial-view-and-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!