Abhijeet
Abhijeet

Reputation: 13906

Render Partial View only after HttpPost ActionHandler

I am making WCF service call using MyViewRequest view fields inside HttpPost ActionHandler. The goal is to show response using partial view, MyViewResponse

In brief I need to achieve these two items-

  1. Disable load of partial view on first load.
  2. Display Response (along with Request) after service call.

MyViewRequest.cshtml

@using (Html.BeginForm())
{
    @Html.ValidationSummary(false)
    //html code
}
</div>
<div id="dvResponse">
  @Html.Partial("MyViewResponse");
</div>

Partial view: MyViewResponse.cshtml

@model MvcApplication3.Models.MyModel
@{
    ViewBag.Title = "MyViewResponse";
}

<h2>MyView</h2>

@Html.Label(Model.MyName, "My Name")

This was pretty straight forward in Asp.Net using userControl, But stuck up here, How can we achieve this in MVC3.

Upvotes: 0

Views: 1564

Answers (1)

Shyju
Shyju

Reputation: 218852

I think the best way is to transfer your data using ViewModels. Let's assume you want to have an app something like stackoverflow where you have a question and user can post an answer and it will be shown after the post along with the question.

public class PostViewModel
{
  public int ID { set;get;}
  public string Text { set;get;}
  public List<PostViewModel> Answers { set;get;}
  public string NewAnswer { set;get;}
}

in your GET action, you show the question. Get the id from the url and get the Question details from your service/repositary.

public ActionResult Show(int id)
{
  var post=new PostViewModel();
  post=yourService.GetQuestionFromID(id);
  post.Answers=yourService.GetAnswersFromQuestionID(id);
  return View(post);  
}

Assuming yourService.GetQuestionFromID method returns an object of PostViewModel with the propety values filled. The data can be fetched from your database or via a WCF service call. It is up to you. Also yourService.GetAnswersFromQuestionID method returns a list of PostViewModel to represent the Answers for that question. You may put both these into a single method called GetQuestionWithAnswers. I wrote 2 methods to make it more clear.

Now in your Show view

@model PostViewModel
@Html.LabelFor(x=>x.Text);
@using(Html.Beginform())
{      
  @Html.HiddenFor(x=>x.ID);     
  @Html.TextBoxFor(x=>x.NewAnswer)
  <input type="submit" />
}
<h3>Answers</h3>
@if(Model.Answers!=null)
{
  @Html.Partial("Responses",Model.Answers)
}

And your Partial view will be strongly typed to a collection of PostViewModel

@model List<PostViewModel>
@foreach(var item in Model)
{
  <div> @item.Text </div>
}

Handling the postback is simple (HttpPost)

[HttpPost]
public ActionResult Show(PostViewModel model)
{
  if(ModelState.IsValid)
  {
    //get your data from model.NewAnswer property and save to your data base 
    //or call WCF method to save it.
    //After saving, Let's redirect to the GET action (PRG pattern)
    return RedirectToAction("Show",new { @id=model.ID});
  } 
}

Upvotes: 2

Related Questions