ASP.NET MVC3: Interaction between Partial View and Main View

前端 未结 3 762
难免孤独
难免孤独 2020-12-20 09:55

I have a partial view for contact. Currently the index view shows this partial view for contact details. There is a save button inside the partial view to save the edited d

相关标签:
3条回答
  • 2020-12-20 10:25

    As data is posted to "HomeController" and "Index" action, so changes are reflected when you change age in View.

    Try to modify the home controller as follows,then it will work as expected.

    1) Instead of having a list of AgeHoroscope, we can have a dictionary of age and prediction.

    2) Create two Index Action for HttpGet and HttpPost as follows.

    public class HomeController : Controller
    {
    
        Dictionary<int, string> AgePred = new Dictionary<int, string>()
        {
        {16,"You are confused"},
        {26,"You are very brilliant"},
        {27,"You are practical"}
        };
    
        [HttpGet]
        public ActionResult Index()
        {
            AgeHoroscope selectedHoro = new AgeHoroscope() { Age = 26 };
            selectedHoro.HoroscopePrediction = AgePred[selectedHoro.Age];
            return View(selectedHoro);
        }
        [HttpPost]
        public ActionResult Index(AgeHoroscope model,ContactEntity entity)
        {
            model.Age = entity.ContactAge;
            model.HoroscopePrediction = AgePred[entity.ContactAge];
            return View(model);
        }
    
    }
    
    0 讨论(0)
  • 2020-12-20 10:34

    I would like just use jQuery to do ajax post and then change the parent view client side directly

    0 讨论(0)
  • 2020-12-20 10:50

    you'll need to create a new ViewModel to do this. This ViewModel (IndexViewModel.cs) would look something like this (I'm guessing at this):

    public class IndexViewModel
    {
        public int ContactID { get; set; }
        public string ContactName { get; set; }
        public int ContactAge { get; set; }
        public string HoroscopePrediction { get; set; }
    }
    

    you'd then use it in your controller index action (and view):

    @model  MYContactEditPartialViewTEST.IndexViewModel
    

    the idea being that you'd populate the HoroscopePrediction in a join between ContactEntity and AgeHoroscope (or via Linq etc) and thus show each line in the index as a complete object (showing contact and horoscope).

    0 讨论(0)
提交回复
热议问题