I've been trying to load a partial view but when clicking the link it inserts the whole site instead of just the partial view. What am I doing wrong?
In my template I have:
#Ajax.ActionLink("View list",
"List",
"SwitchView",
new AjaxOptions()
{
UpdateTargetId = "testajax",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
})
<div id="testajax"></div>
#section Scripts {
<script src="#Url.Content("~/Assets/framework/js/unobtrusive-ajax/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
}
My controller:
public class SwitchViewController : Controller
{
public PartialViewResult List()
{
return PartialView("~/Views/Partials/kund.unikum.se/_ListView");
}
}
I've also added these settings in web.config since they were missing:
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
Also, when looking at the generated html link it's missing a "href" value?
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#testajax" href="">View list</a>
Screenshot of the loaded resources and the view
Have you set Layout=null in the partial view? if not then set and check. let me know if you still facing the issue.
Related
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>
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");
}
I'm trying to use an Ajax.BeginForm. When I submit, I want to render a partial view. Everything is working fine, but the InsertionMode = InsertionMode.Replace is not working, it opens the partial view in a new window.
I have also an Ajax.ActionLink in the same page, and that is working fine.
I have already added the jquery.unobtrusive-ajax.js and it still doesn't work. Also, in the web.config I have
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
Here is my code from the view:
<div id="div_to_replace">
#using (Ajax.BeginForm("Edit", "MyController", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "div_to_replace" })){
<div class="editor-field">
#Html.EditorFor(model => model.name)
#Html.ValidationMessageFor(model => model.name)
</div>
<input type="submit" value="Save" />
}
</div>
And my controller:
[HttpPost]
public ActionResult Edit(MyObject object)
{
try
{
if (ModelState.IsValid)
{
updateModel(object)
return PartialView("_MyPartilView", model);
}
else
{
return PartialView(object);
}
}
catch
{
return PartialView(object);
}
}
Thanks!
I have found the problem. I was using the last jquery version (1.9.1) and it doesn't work with the original jquery.unobtrusive-ajax.js file.
I changed to jquery version 1.4.4 (the one that comes by default when you create an asp.net mvc 3 project) and the problem was solved.
Make sure you have jQuery included.
Make sure you have a div with ID div_to_replace.
Make sure UnobtrusiveJavaScriptEnabled is active, on your web.config in Views folder
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
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
How to client side validate the dropdownlist box.....
#Html.DropDownListFor(per => per.Gender, new[] {
new SelectListItem(){Text = "Male" , Value="Male"},
new SelectListItem(){Text ="Female" , Value = "Female"},
}, "Select Your Gender")
#Html.ValidationMessageFor(per => per.Gender)
Include jquery validate plugin scripts in your view along with jQuery (if not already refered in the Layout.cshtml)
#model SomeModel
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm())
{
#Html.DropDownListFor(per => per.Gender, new[] {
new SelectListItem(){Text = "Male" , Value="Male"},
new SelectListItem(){Text ="Female" , Value = "Female"},
}, "Select Your Gender")
#Html.ValidationMessageFor(per => per.Gender)
<input type="submit" />
}
And make sure the SomeModel's Gender property is required
[Required]
public string Gender { set;get;}
Update your web.config to and set the AppSetting called ClientValidationEnabled to true
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Now when you submit, it will execute the client side validation, if javascript is enabled in the browser.