partial view display with targeted div in MVC3 Razor view engine - asp.net-mvc-3

My Controller Action is:
public ActionResult PVInPage()
{
return View();
}
public ActionResult ViewPage2()
{
return PartialView();
}
My Main View:
#using (Html.BeginForm("ViewPage2", "PartialViewInPage"))
{
<input type="submit" value="Call Page Two" />
}
<div id="DisplayPartilView">
#*display partial view *#
</div>
My Partial view Is :
#{
ViewBag.Title = "View Page 2";
}
<div style="width:500px; height:200px; background-color:Gray" >
<h1> This is my Partial view </h1>
</div>
Now I want to do : when i click submit button in my main view then my partial view arise in
My main view inner div with id="DisplayPartilView".
Thanks for response

If you want to load data/html into a page without navigating to a different page you need to use Ajax.
ASP.Net MVC provides a set of helpers to work with Ajax (they are all use jQuery.Ajax under the hood so you can always drop back to one level and write your ajax calls by hand).
But in your case the Ajax.BeginForm provides everything what you need:
So change your main view to:
#using (Ajax.BeginForm("ViewPage2", "PartialViewInPage",
new AjaxOptions() { UpdateTargetId = "DisplayPartilView" }))
{
<input type="submit" value="Call Page Two" />
}
<div id="DisplayPartilView">
#*display partial view *#
</div>
And to make it work you need to reference the following script in your main view or in your layout file after jQuery:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

#using (Html.BeginForm("ViewPage2", "PartialViewInPage"))
will refresh page, that's why you need ajax
.serialize() to get data from all inputs and .ajax() to make post request, then set partial:
$('#DisplayPartilView').html(response);

In my project i am doing like this it's below
this is my button which is i click then my partial view load in my div like this
<script type="text/javascript">
$(function () {
$("#btnLode").click(function () {
$("#LodeForm").load("/City/ShowAllState", function () {
alert("Your page loaded Successfully !!!!!!!");
});
});
});
</script>
<div id="LodeForm">
</div>
and this is another solution for this problem
#using (Ajax.BeginForm("SearchCountry", "City",
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "Get",
LoadingElementId = "ajax-loader",
UpdateTargetId = "CountryListID",
}))
{
<input type="submit" value="search Country" data-autocomplete-source="#Url.Action("SearchCountry", "City")" />
}
<div id="CountryListID">
</div>
i think this will help you

Related

Ajax.BeginForm preload data

I have this view and everything fine with Ajax.BeginForm:
<h2>Index</h2>
#using (Ajax.BeginForm("Search", new AjaxOptions {
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "users"
})) {
<input name="q" type="text" />
<input type="submit" value="Search" />
}
<div class="table-responsive" id="users">
</div>
But, i have a little question.
Right now, when i open this page, there are no table with data - it loads only when form is submitted.
So, my question: is it possible to have preload data (without adding other code)?
When page is loaded, i would like to have already all data without filtering (input uses for filtering when value is typed and form submitted).
Just call your Search action from users div when the page loads. You may not specify any parameter or use the default one. I assume you have something like this:
public ActionResult Search(string q)
{
var users = _usersRepository.GetAll();
if(!string.IsNullOrEmpty(q))
users = users.Where(user => string.Equals(user.Name, q));
return PartialView("_Search", users);
}
And in the view:
<div class="table-responsive" id="users">
#Html.Action("Search")
</div>

How do I refresh a second partial view, after the first partial view is updated?

I have a page which has a partial view (it's a login form). When the submit button is clicked, it calls the controller and logs the person in and refreshes the login form to show that he is logged in.
I now need to update the portion of the screen that shows the login button, or if he is logged in, shows "Hello, Logged In user"
I have a partial view written that shows whether or not the person is logged in, but I don't know how to call it after the success of the first one. I know there is an OnSuccess event, and that seems to be where I would wire that up, but I am not sure how to do this.
#using (Ajax.BeginForm("Login", "Account", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "loginSection", }))
{
<div id="loginSection">
...form omitted for clarity.
<input type="submit" value="Log in" />
</div>
}
This is the partial view that needs to be updated after the login.
<ul id="menu">
#if (Request.IsAuthenticated)
{
<text>
Hello, #User.Identity.Name
</text>
}
else
{
<ul>
<a onclick="openLoginWindow()">Login</a>
<a onclick="openRegisterWindow()">Register</a>
</ul>
}
Instead of using Ajax.BeginForm, use normal form and do the form posting with your custom code so that you can controll the success handler as you wish
<div id="login">
#using(Html.Beginform())
{
<input type="text" name="UserName" />
<input type="text" name="Password" />
<input type="submit" id="btnLogin" />
}
</div>
and the script which will listen to the submit button click event and send the form the action method.
$(function(){
$("#btnLogin").click(function(e){
e.preventDefault();
var _this=$(this);
var _form=_this.closest("form");
$.post(_form.attr("action"),_form.serialize(),function(res){
if(res.Status==="authenticated")
{
//Let's hide the login form
$("#login").hide();
$("#yourSecondDiv").html(res.PartialViewContent);
}
else
{
alert("Wrong password");
}
});
});
});
So the javascript code is expecting a JSON structure like below from the controller action
{
"Status":"Authenticated",
"PartialViewContent" : "<p>The markup you want to show</p>"
}
the PartialViewContent will hold the markup you want to show to the user.
public ActionResult Login(string UserName,string Password)
{
//to do : Build the JSON and send it back
}
This answer will tell you how send the markup of a partial view in a JSON property to client.
Here is what worked for me:
Added OnSuccess:
#using (Ajax.BeginForm("Login", "Account", new AjaxOptions {
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "loginSection",
OnSuccess = "successfulLogin"
}))
{... details omitted.
Then added this:
function successfulLogin() {
$('#loginPartial').load('Account/LoginLinksPartial');
which calls in the controller:
public ActionResult LoginLinksPartial()
{
return PartialView("_LoginLinks");
}

How to use Ajax to update RenderBody() section with VS 2012 Internet Template?

I've looked at few examples where Ajax can be used to update divs or other elements with ids. I have not been able to find an example that uses Ajax with Razor views to help me with the following.
My page is a standard Menu at the top, body in the middle, and a footer. There is no real need to update the header and footer each time. In fact, my page only requires a section of the Body to be updated based on menu clicks and actionlinks on the page. I'm testing this with the Internet Template that is created using VS 2012 if that helps such that I do not have to clutter this request with a bunch of code snippets. I am using Razor views and C# for coding preferences.
So, given the default _Layout.cshtml file, how would I load the About page i.e. RenderBody() section via Ajax? I've tried adding Ajax.BeginForm(...) to my _Layout.cshtml file around one div with an UpdateTargetId that matches a div that I wrapped around the RenderBody() call, returned a partial view from my controller, but that's not quite right. What I get is my partial view only. (The About page with no menu, footer, etc. just the code on the About page)
Would someone kindly share a link that demonstrates this functionality or kindly share the code that does what I desire i.e. swap index view with about view without a full page refresh? Some explanation of what I'm missing would be nice, but I'm sure I could deduce from a solid example where I went awry. As always, your time is much appreciated.
EDIT: Using Jasen's suggestion
_Layout.cshtml
<nav>
<ul id="menu">
<li>#Html.ActionLink("Home", "Index", "Home")</li>
<li>#Ajax.ActionLink("About", "About", "Home", null, new AjaxOptions { HttpMethod = "get", UpdateTargetId = "body" }, new { })</li>
<li>#Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</nav>
....
Inside my div id="body"
#RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix">
#RenderBody()
</section>
.....
HomeController.cs
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return PartialView();
}
......
Here is a simple example with jquery. The About partial gets injected into the div with id="body".
<button>About</button>
<div id="body"></div>
$(function () {
$("button").on("click", function(e) {
$.get("Home/About").done(function(result) {
$("#body").html(result);
});
});
));
Controller Action
[HttpGet]
public ActionResult About()
{
return PartialView("About");
}
About.cshtml
#{ Layout = null }
<h2>Home/About</h2>
<p>Blah... </p>
Edit: Maybe a better example is to use a link instead
#Html.ActionLink("About", "About", "Home", null, new { #class="menu-button" })
<div id="body"></div>
$(function () {
$(".menu-button").on("click", function(e) {
e.preventDefault();
var url = $(this).attr("href");
$.get(url).done(function(result) {
$("#body").html(result);
});
});
});
Edit: Without jquery you want to use Ajax.ActionLink() instead of Ajax.BeginForm()
#Ajax.ActionLink("About", "About", "Home", null, new AjaxOptions { HttpMethod = "get", UpdateTargetId = "body" }, new { })
<div id="body"></div>
In your HomeController.cs
public PartialViewResult About()
{
ViewBag.Message = "Your app description page.";
return PartialView();
}
In your _Layout.cshtml do not forget to import:
<script src="~/Content/Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="~/Content/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>

MVC4 - Ajax.BeginForm and Partial view gives 'undefined'

I'm working on an activity booking and I'm having trouble using ajax.beginform with a partial view. When I click submit, it just goes to a new page and there is an 'undefined' in the top left corner. I have "../../Scripts/jquery.unobtrusive-ajax.min.js" in my layout page. What I want to do is when the user submits the form, the div "AjaxTest" gets updated with the partial view and the form is under the search results.
Here is what I have so far (I took out all the structure and styling so its easier to read):
Main View - Activities
#model Project.Models.ActivityModel
<div id="AjaxTest"></div>
#using (Ajax.BeginForm(new AjaxOptions
{
UpdateTargetId = "AjaxTest",
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST"
}))
{
#Html.ValidationSummary(true)
#Html.TextBoxFor(x => x.Activity_CityName)
<div class="editor-label">
<strong>#Html.LabelFor(x => x.Activity_StartDate)</strong>
</div>
<div class="editor-field">
<input id="checkin" type="text" name="Activity_StartDate" />
</div>
#Html.TextBoxFor(x => x.Activity_EndDate)
#Html.DropDownListFor(x => x.Activity_NumAdults, AdultNum)
#Html.DropDownListFor(x => x.Activity_NumChildren)
#Html.DropDownListFor(x => x.Activity_ChildAge1, ChildAge)
#Html.DropDownListFor(x => x.Activity_ChildAge2, ChildAge)
#Html.DropDownListFor(x => x.Activity_ChildAge3, ChildAge)
<div class="submitbutton">
<input data-inline="true"type="submit" id="activity_search" value="Search" />
</div>
}
Controller
[HttpPost]
public ActionResult Activities(ActivityModel activitysubmission) {
return PartialView("PartialActivities_Success", activitysubmission);
}
Partial View - PartialActivities_Success
#model Project.Models.ActivityModel
<p>City: #Model.Activity_CityName</p>
<p>StartDate: #Model.Activity_StartDate</p>
<p>EndDate: #Model.Activity_EndDate</p>
<div>
<p><strong>Ticket</strong></p>
<p>Number of Adults: #Model.Activity_NumAdults</p>
<p>Number of Children: #Model.Activity_NumChildren</p>
<p>Child 1 age: #Model.Activity_ChildAge1</p>
<p>Child 2 age: #Model.Activity_ChildAge2</p>
<p>Child 3 age: #Model.Activity_ChildAge3</p>
</div>
Scripts in Layout Page
<script src="../../Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"> </script>
<script src="../../Scripts/xdate.js" type="text/javascript"></script>
<script src="../../Scripts/xdate.i18n.js" type="text/javascript"></script>
<script src="#System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/js")"></script>
<script>
$(document).bind("mobileinit", function() {
// As of Beta 2, jQuery Mobile's Ajax navigation does not work in all cases (e.g.,
// when navigating from a mobile to a non-mobile page, or when clicking "back"
// after a form post), hence disabling it.
$.mobile.ajaxEnabled = true; // originally false.
});
</script>
I noticed one mistake in the code. Your div has an id Ajaxtest but the parameter you are passing to BeginRequest is AjaxTest the T is capital
Are you using MVC 4? I would make sure that UnobtrusiveJavaScriptEnabled is set to true in your WebConfig file. I believe it is by default, though. The only other thing I can think of is to verify that you have your other jQuery files and that they're being loaded in the right order. If you load your unobrusive jQuery file before the main one then it won't work.
You haven't specified which action to call when posting the Ajax form. Try changing it to this:
#using (Ajax.BeginForm("Activities", new AjaxOptions
{
UpdateTargetId = "AjaxTest",
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST"
}))

MVC3 with Ajax - return data not "plugged" to the right spot

I'm trying to get started with Ajax on MVC
In my main view I have the following code:
#Ajax.ActionLink("Click here to get the data","LoadData",
new AjaxOptions
{
UpdateTargetId = "dataPanel",
InsertionMode = InsertionMode.InsertAfter,
HttpMethod="GET"
})
<div id="dataPanel">
</div>
I created the controller's action as below:
public PartialViewResult LatestReview()
{
var myData = GetMyData();
return PartialView("_PartialData", myData);
}
_PartialData is defined as below:
#model MyApp.Models.Data
<div>
#if (Model == null)
{
<p>There is no data yet</p>
}
else
{
<p>
#Model.Body
</p>
}
</div>
But when I click the link, my data (rendered in the _PartialData) is loaded fully in browser, replacing the source page (so not inside the dataPanel div)
When I look at original page source (before clicking the ajax link) It see the ajax actions define as below:
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="after" data-ajax-update="#dataPanel" href="/Home/LoadData">Click here to get the data</a>
<div id="dataPanel">
</div>
What am I doing wrong?
Thanks
I suspect that you forgot to include the jquery unobtrusive ajax script to your page:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
It is this script that makes sense of all Ajax.* helper in ASP.NET MVC 3. Without it they generate standard markup with HTML5 data-* attributes which are used by the script.

Resources