I have a very simple view that has a DropDownListFor and a Button inside an Ajax.BeginForm helper. Clicking the button renders the whole view again inside the div I have set to update including the layout page (I also notice a spike in the cpu when clicking the button multiple times)
Here is the Ajax.BeginForm inside the view:
#using (Ajax.BeginForm("About2", "Home", new AjaxOptions { UpdateTargetId = "property22" }))
{
<div>
<div id="property22">
#Html.DropDownListFor(m => m.SomePropertyToBind, new SelectList(Model.list, "property1", "property2"))
</div>
<button type="submit" id="test">
Click me</button>
</div>
}
Any ideas where I'm going wrong?
I uploaded the whole project if someone has a couple of minutes to take a look at it:
http://www.sendspace.com/file/siu3r31 (free provider so there may be a popup)
Thanks
You are using a wrong overload of the Ajax.BeginForm helper. It should be like this:
#using (Ajax.BeginForm(
"About2",
"Home",
null,
new AjaxOptions { UpdateTargetId = "property22" },
new { #id = "refreshe" }
))
Notice the additional null value I am passing as the routeValues parameter. Also in the example you uploaded you forgot to include the TestView.cshtml view. This being said in order to fix the problem you have two possibilities:
Either return a partial view:
public ActionResult About2()
{
Random randomizer = new Random();
int random = randomizer.Next(1, 1000000000);
ModelTest newModelTest = new ModelTest();
string[] stringList = new string[] { "Red", "Blue", "Green" };
newModelTest.list = from test in stringList
select new ModelTestList
{
property1 = test,
property2 = test
};
newModelTest.SomePropertyToBind = stringList[random % 2];
return PartialView("TestView", newModelTest);
}
or disable the layout in the TestView.cshtml view:
#{
Layout = null;
}
Unfortunately from your explanation above and from the code, I am not sure what you are trying to achieve. However, I think your most worry is about having Ajax working in your view.
In your About2 action method, you are trying to return a complete view which is TestView (in that case, it doesnt exist) and passing it the newModelTest view Model. I would advise changing to return either a PartialView or JsonResult.
For example, changing the return statement of About2 action method to
public ActionResult About2()
{
...
return Json(newModelTest);
}
or changing it to a return type to string and returning "TestResult"
public String About2()
{
...
return "TestResult";
}
or you could change the return statement to return a PartialView
Thanks for your replies.
I just realized that About2 should have returned the "About" view instead of the "TestView". I had tried creating a partial view with the Ajax.BeginForm code but I came across the same problem.
This is my first attempt at Ajax.BeginForm (so far I have always used jquery), and I was under the impression that it works in a similar fashion in the sense that by specifying the target id only the contents of that element will get updated, not that the target will actually get replaced by the whole response object.
Thanks for your help, not only did I get it to work, but I now understand how it should work.
I suspect that what's happening is that you're returning the a complete View (including the layout template) in the Ajax response. Try changing your "Home" controller "About2" action temporarily to the following:
public ContentResult About2() {
return Content("Hello World");
}
I tested this sample Action with your Razor markup and clicking the button properly replaced your dropdown list with "Hello World!".
If this is indeed what's happening, then you'll want to return a View from "About2" without the layout by declaring the following at the top of the View that you're returning.
#{
Layout = null;
}
Related
I want to show a success message after calling the following ajax.beginform
from Index view
#using (Ajax.BeginForm("Insert", "Home", new AjaxOptions() { UpdateTargetId = "result", HttpMethod = "POST" }))
{
#Html.TextAreaFor(m => m.openion)
}
this is my result div
<div id="result">
</div>
and my controller is
[Httppost]
public ActionResult InforMessage(openionModel usr)
{
return Content("Thanks for adding your openion");
}
but when i try this it is going to another view InforMessage
It is not updating the result div.
There is no Informessage Exist. Still it open a new page with message
"Thanks for adding your openion".How to solve this?
If your redirecting to another page its because you do not have the correct scripts loaded (or have duplicates or have them in the wrong order) so its doing a normal submit.
Ensure you have included (in order)
jquery-{version}.js
jquery.unobtrusive-ajax.js
Say I have the following button
<button id="CopyUsersRolesButton" type="button" onclick="CopyUsersRoles()" data-url="#Url.Action("CopyUsersRoles", "Index", new {userId = "0" })">
Copy Users Roles</button>
I want to redirect to a view that is returned by the following action:
public ActionResult CopyUsersRoles(int userId)
{
var model = new CopyUsersRolesViewModel
{
SelectedUserId = userId
};
return View(model);
}
I need to pass a javascript variable (SelectedUserId) to the action.
The only way I've got it to work is by keeping a placeholder in the URL.Action method and replacing it as follows:
function CopyUsersRoles() {
var url = $('#CopyUsersRolesButton').data('url');
window.open(url.replace('0', SelectedUserId));
return false;
}
This feels very hacky to me, is there not a cleaner solution? I don't currently have a form on the html page and would like to avoid using an input button as all the other buttons have Jquery UI icons (see How to add jQuery UI Button icons to input buttons?).
I'm working on the admin part of an MVC webapp. I had the idea to use "widgets" for a single Admin panel. I'll explain my intentions first.
I have a languages table, and for that I'd like to create a partial view with a dropdownlist for those languages and a single button "Edit", that would take the user to a non-partial view to edit the language. After clicking save, the users would be redirected to the Index view, which would just show the dropdownlist again.
So I have a "Index.cshmtl", and an "EditLanguage.cshtml" as non-partial views, and a "LanguageWidget.cshtml" as a partial view.
First the user sees the Index view.
public ViewResult Index()
{
return View();
}
This view has the following code in it:
#using CodeBox.Domain.Concrete.ORM
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Administration</h2>
#Html.Action("LanguageWidget")
The Partial view "LanguageWidget" just contains the following code, and when the user submits it posts to the HttpPost annotated method in my controller:
#using (Html.BeginForm("LanguageWidget", "Admin"))
{
#Html.DropDownListFor(model => model.SelectedItem, Model.Languages)
<input type="submit" value="Edit"/>
}
This is the HttpPost method for the widget:
[HttpPost]
public ActionResult LanguageWidget(LanguageWidgetModel model)
{
var lang = langRepo.Languages.FirstOrDefault(l => l.LanguageId == model.SelectedItem);
return View("EditLanguage", lang);
}
This takes the user to the language edit page, which works fine.
But then! The user edits the language and submits the page, which invokes the "EditLanguage" HttpPost method, so the language is saved properly.
[HttpPost]
public ViewResult EditLanguage(Language model)
{
if (ModelState.IsValid)
{
langRepo.SaveLanguage(model);
TempData["message"] = string.Format("{0} has been saved!", model.Name);
return View("Index");
}
else
{
return View(model);
}
}
So, when I return the "Index" view - which seems logical I guess - the controller still assumes this is a HttpPost request, and when it renders the Index view, it invokes the "LanguageWidget" method, assuming it has to render the HttpPost method.
This leads to the LanguageWidget HttpPost method, which returns a full view with layout, returning just that, so I have my layout, with view, containing a layout, with the editview.
I don't really see how I could fix this?
I'm pretty sure it's a design flaw from my part, but I can't figure it out.
Thanks in advance!!
Consider using:
return RedirectToAction("Index")
instead of:
return View("Index");
It might seem more logical if the user is actually redirected to Index instead of
remaining at the EditLanguage. And if the user hits the refresh button no data will be resent using this approach.
I'm trying to render a particular section/div click a particular link or button. Suppose link/button is in the A.cshtml page , and b.cshtml is a partial view that I want to load in A.cshtml page within a particular section/div. I tried Ajax.ActionLink but can't do. Any help or suggestions?
I tried ajaxactionlink but cant do
That's really not the way to ask a question here. Cant do is not a precise problem description. Next time when you ask a question on SO show what you have tried.
This being said, let me provide you with an example:
#Ajax.ActionLink("click me", "SomeAction", new AjaxOptions {
UpdateTargetId = "result"
})
<div id="result"></div>
and then you will have an action which will render this partial view:
public ActionResult SomeAction()
{
return PartialView("_NameOfYourPartial");
}
Finally make sure that you have referenced the jquery.unobtrusive-ajax.js script to your page which uses the HTML5 data-* attributes emitted by the Ajax.ActionLink helper to hijack the click event and send an AJAX request instead of the normal request:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
The controller can return a partial view as action result:
public ActionResult Details()
{
var model = // your model
var viewName = // your partial view name
return PartialView(viewName, model);
}
Ajax.ActionLink should do it, may be you missed somwthing.
Check this post it may give you the answer
I have a Controller listed below:
//
// GET: /Customer/Details/5
public ActionResult Details(short id)
{
ActionResult actionResult = null;
if (HttpContext.User.IsInRole("Admin"))
{
// this is the logic that is getting executed
YeagerTechWcfService.Customer cust = db.GetCustomerID(Convert.ToInt16(id));
actionResult = View("Details", cust); }
else
{
HttpCookie cn = Request.Cookies["strCookieName"];
if (cn != null)
{
YeagerTechWcfService.Customer cust = db.GetCustomerID(Convert.ToInt16(id));
actionResult = View("Details", cust);
}
else
{
TempData["ErrCode"] = "CustView";
actionResult = RedirectToAction("Index", "Home");
}
}
return actionResult;
}
I have a View (where the ActionLink is) like below:
columns.Template(
#<text>
#Ajax.ActionLink("Detail", "Details", "Customer", new { id = item.CustomerID },
new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "detailCustomer" })
</text>
).Width(70);
The rendered output is now as follows:
<a data-ajax="true" data-ajax-mode="replace" data-ajax-update="#detailCustomer" href="/Customer/Details/2">Detail</a>
If I click on the link from within the source view of the browser, I get to my new View just fine.
However, if I try and click on the ActionLink, the View doesn't come up. I can verify during debugging, that I'm stepping thru the Details View after I hit that controller code. The present view just stays in place without switching to the new View.
Moreover, I can see that if I click on the ActionLink, it executes the same exact code (during debugging) as when I paste it into the address bar:
http://localhost:4514/Customer/Details/2
When I click on the ActionLink, even though the same code is executed, the address url doesn't change to the above. and the View is not being rendered.
What am I doing wrong?
even though the same code is executed, the address url doesn't change
to the above
You are using an Ajax.ActionLink meaning that it will send an AJAX request. The whole point of AJAX is to stay on the same page and not redirect.
You indicate UpdateTargetId = "detailCustomer" so make sure that in your page you have a container with this id:
<div id="detailCustomer"></div>
which will be updated with the results of the AJAX call. Also make sure that you have properly included the jquery.unobtrusive-ajax.js script to your page in order for the Ajax.ActionLink helper to do anything useful.
On the other hand if you want to perform a full postback and change the url of your browser you probably need a standard link:
Html.ActionLink("Detail", "Details", "Customer", new { id = item.CustomerID }, null)