How to pass an actionlink's results to a partialview placeholder? - asp.net-mvc

Okay, so in my page I have a list of links:
#foreach (var item in Model)
{
#Html.ActionLink(item.Name, "Recruitments", new { Id = item.Id })
<br />
}
And what I want is for the partialview to return somewhere else on the page, in a placeholder I've set aside.
Is this possible? Or do I have to use jquery ajax calls instead somewhere?

you can #Ajax.ActionLink in asp.net mvc, it has different overloads you can use according to your requirements here is the code:
#Ajax.ActionLink("ActionName", // action name
"Recruitments", //controller name
new { Id = item.Id }, // route values
new AjaxOptions { HttpMethod = "GET", //HttpMethod Get or Post
InsertionMode = InsertionMode.Replace, // Replace content of container
UpdateTargetId = "Container", // id of element in which partial view will load
OnComplete = "Completed();" }) // js function to be executed when ajax call complete
<div id="Container">
</div>
<script>
function Completed()
{
alert("completed");
}
</script>

I did had a problem with partial for your problem post some code so I understand your problem.
Either you should use a razor helper, either you simply use jquery to manipulate the dom.
note that jquery is pretty simple
$("#selectorOnYourPlaceHolder").html($("#selectorOnYourLinks").html());
$("#selectorOnYourLinks").html("")

You want to do this with Ajax:
$.ajax({
type: "GET", url: "somePageOrHandler.aspx", data: "var1=4343&var2=hello",
success: function(data)
{
$('#someDivInPlaceHolder').html( data);
}
});

Related

View is not displaying after Post Request

I'm making a post request from on view so that I don't see the parameters on the URL and I can tell it is passing the appropriate parameters to controller for the request but it does not display the appropriate view from that controller.
Calling view
#Ajax.ActionLink("Work1", "NewIndex", "WorkItems",
new
{
eventCommand = "createforrig",
//eventArgument1 = #item.Id,
eventArgument2 = #item.Id
},
new AjaxOptions
{
HttpMethod = "POST"
})
WorkItems Controller method
[HttpPost]
public ActionResult NewIndex(NewWorkItemViewModel vm)
{
vm.IsValid = ModelState.IsValid;
vm.HandleRequest();
if (vm.IsValid)
{
// NOTE: Must clear the model state in order to bind
// the #Html helpers to the new model values
ModelState.Clear();
}
else
{
foreach (KeyValuePair<string, string> item in vm.ValidationErrors)
{
ModelState.AddModelError(item.Key, item.Value);
}
}
return View(vm);
}
Putting a breakpoint on the last Return View(vm) confirms it is being called but the browsers does not update to display the workItems view.
Suggestions on why the browser is not being updated to display the appropriate view.
You're making an ajax post, the newly rendered view is being returned by the server if you were to look in the network console in your browser. Add a success callback. Either assign a callback to handle the response or use the
UpdateTargetId property in your AjaxOptions
#Ajax.ActionLink("Work1", "NewIndex", "WorkItems",
new
{
eventCommand = "createforrig",
//eventArgument1 = #item.Id,
eventArgument2 = #item.Id
},
new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "AjaxSuccess", //handle with callback
UpdateTargetId = "MyElementID" //update html element
})
if you choose to use OnSuccess then in javascript
function AjaxSuccess(data){
//handle response
}
AjaxOptions properties and usage can be found here
EDIT
You could use javascript to submit a form when a link is clicked, put a form somewhere in your code and hide it.
#using (Html.BeginForm("NewIndex", "WorkItems", FormMethod.Post,
new { class = "hidden", id = "postForm" } ))
{
<input type="hidden" name="eventCommand" value="createforrig" />
<input type="hidden" name="eventArgument2" value="#item.Id" />
<input type="submit" value="link text" id="submitForm"/>
}
then change your #Ajax.ActionLink... to
#Html.ActionLink("Work1", "NewIndex", "WorkItems", new { id = "postLink"})
and if you're using jQuery
<script>
$(function(){
$('#postLink').click(function(e)
{
e.preventDefault();
$('#postForm').submit();
});
});
</script>
and don't forget to hide the form in css
.hidden { display:none;}

How to Pass textbox value using #html.actionlink in asp.net mvc 3

How to Pass value from text using #html.actionlink in asp.net mvc3 ?
None of the answers here really work. The accepted answer doesn't refresh the page as a normal action link would; the rest simply don't work at all or want you to abandon your question as stated and quit using ActionLink.
MVC3/4
You can use the htmlAttributes of the ActionLink method to do what you want:
Html.ActionLink("My Link Title", "MyAction", "MyController", null, new { onclick = "this.href += '&myRouteValueName=' + document.getElementById('myHtmlInputElementId').value;" })
MVC5
The following error has been reported, but I have not verified it:
A potentially dangerous Request.Path value was detected
Rather than passing your value using #Html.actionlink, try jquery to pass your textbox value to the controller as:
$(function () {
$('form').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: { search: $('#textboxid').val()},
success: function (result) {
$('#mydiv').html(result);
}
});
return false;
});
});
This code will post your textbox value to the controller and returns the output result which will be loaded in the div "mydiv".
to pass data from the client to the server you could use a html form:
#using (Html.BeginForm(actionName,controllerName)) {
<input type="text" name="myText"/>
<input type="submit" value="Check your value!">
}
be sure to catch your myText variable inside your controller's method
you can use this code (YourValue = TextBox.Text)
Html.ActionLink("Test", new { controller = "YourController", action = "YourAction", new { id = YourValue }, null );
public class YourController : Controller
{
public ActionResult YourAction(int id)
{
return View("here your value", id);
}
}

Search and display on same page in mvc2 asp net

have a simple search form with a textbox. And upon submitting the form I send the contents of the textbox to a stored procedure which returns to me the results. I want the results to be displayed on the same page the form was, except just below it.
Right now I'm doing the following but it's not working out exactly the way I want:
sathishkumar,
You don't tag the question as being an ajax related solution or not. I'm going to present a simple ajax approach which may or may not be suitable.
in the controller:
public ActionResult Search(string searchTerm)
{
// you don't add code re your stored proc, so here is a repo based approach
var searchItems = _repository.Find(x => x.searchfield.Contains(searchTerm));
return PartialView("SearchPartial", searchItems);
}
main view (index.aspx or whatever) (below where your main content is defined, add):
<div id="searchResults"></div>
in another part of the page (semi psuedo-code):
<script type="text/javascript">
function getSearchResults() {
// #yoursearchbox is a textbox on the index.aspx aview
var tdata = { searchTerm: $('#yoursearchbox').val()};
// or your data in the format that will be used ??
$.ajax({
type: "GET",
data: tdata,
url : '<%= Url.Action("Search", "Home") %>',
success: function (result) { success(result); }
});
});
function success(result){
$("#searchResults").html(result);
}
</script>
You'd then add a partial view SearchPartial.ascx that contained your model for the search results.
Hope this helps.
You can use Ajax to solve the problem.
<div>
`#using (Ajax.BeginForm("action", "controller", new AjaxOptions
{
UpdateTargetId = "results",
HttpMethod = "GET",
}))
{
#Html.TextBox()
<input type="submit" value="Search" />
}`
<div id="results"></div>
</div>

Invoking an action using jquery ajax

I am using ASP.NET MVC 2. I have a modal dialog (done through jquery UI) that contains two text boxes and a button. All the controls are inside a form.
I would like to invoke, when the user click the button, a controller action that do some operations on the passed data contained in the two text boxes and then return an integer value and a string message to the user.
Could anybody provide an example for doing this with jquery?
Thanks so much!
suppose you have the following form :
<form id="ajax-form">
<fieldset>
<input type="text" id="firstname" name="firstname" />
<input type="text" id="lastname" name="lastname" />
<input type="submit" value="send" />
</fieldset>
</form>
using jQuery
$(document).ready(function(){
$("#ajax-form").submit(function(){
$.ajax({
type: "POST",
url: "Person/Add",
data: $("#ajax-form").serialize(),
success: function (response) {
// whatever you want to happen on success
},
error: function (response) {
alert('There was an error.');
}
});
});
});
Accessing Your Data in the Action Method.
public ActionResult Add(FormCollection form)
{
string firstname = form["firstname"];
string firstname = form["lastname"];
// do whatever you want here
// then return something to the view
return Json(/*some object*/);
}
another way is to use Microsoft Ajax
<% using (Ajax.BeginForm("Add", "Person",
new AjaxOptions() {
UpdateTargetId = "formDiv",
InsertionMode = InsertionMode.Replace,
HttpMethod = "Post" })) {%>
<fieldset>
// Form Elements Here.
</fieldset>
<% } %>
UpdateTargetId is the id of the html element to be targeted.
The InsertionMode option has three values Replace, InsertAfter, InsertBefore
Hope that was helpful
Update : you don't have to return a Json result in your action method you can simply return a partial view or any HTML code as the response object and then insert it using jQuery.
You may take a look at the documentation about how you could implement a dialog that contains form fields. And when the confirm button is clicked you could simply send an AJAX request.
buttons: {
Confirm: function() {
// read the value in the textbox
var name = $('#name').val();
// send an AJAX request to an action that will return JSON:
$.getJSON('/home/foo', { name: name }, function(result) {
// read the returned value
alert(result.Value);
});
},
Cancel: function() {
$(this).dialog('close');
}
}
And your controller action:
public ActionResult Foo(string name)
{
return Json(new { Value = '123' }, JsonRequestBehavior.AllowGet);
}

DropDown list onchange event and AJAX in MVC

I have a code block in my MVC view as follows:
<%using (Ajax.BeginForm("MyAction", new { action = "MyAction", controller = "Home", id = ViewData["selected"].ToString() }, new AjaxOptions { UpdateTargetId = "Div1" }))
{ %>
<%=Html.DropDownList("ddl", ViewData["MyList"] as SelectList, new { onchange = "this.form.submit()" })%>
<%} %>
I want to set the value of ViewData["selected"] so that i can send it to the desired action.
Can anyone please suggest how can i do this?
thanks!
Instead of using a form, why not use a jQuery onChange event on your drop down?
$(document).ready(function() {
$("#ddl").change(function() {
var strSelected = "";
$("#ddl option:selected").each(function() {
strSelected += $(this)[0].value;
});
var url = "/Home/MyAction/" + strSelected;
$.post(url, function(data) {
// do something if necessary
});
});
});
ViewData is not the place to pass data back to the server side. Values of html input controls within form tag are conveniently available in action method. You can get these values either from various types of action method arguments (model, formcollection etc).
Here is a link to free asp.net mvc ebook tutorial. Is a good resource for asp.net mvc.
Found solution at this post it is just small chnge
Yes, that’s right – only change is replacing:
onchange = “this.form.submit();”
with:
onchange = “$(this.form).submit();”

Resources