call dropdownlist selected value as #html.action route value - asp.net-mvc

How to call dropdownlist selected value as #html.action route value.
I am using following code in my MVC3 razor. I have to dynamically call 'eventid' as dropdownlist selected value.
#Html.Action("FirmPassForum", "Conference", new { eventId = 69 })

You can't do that, because the Html.Action helper renders at the server, whereas the dropdown selection could change on the client. One possibility is to use an AJAX call. So basically you could subscribe to the .change() event of the dropdown and send an AJAX call to some controller action that will return a partial view and update the DOM.
Start by placing this in a container:
<div id="container">
#Html.Action("FirmPassForum", "Conference", new { eventId = 69 })
</div>
and then:
<script type="text/javascript">
$(function() {
$('#id-of-your-dropdown').change(function() {
var eventId = $(this).val();
$.ajax({
url: '#Url.Action("FirmPassForum", "Conference")',
type: 'GET',
data: { eventId: eventId },
cache: false,
success: function(result) {
$('#container').html(result);
}
});
});
});
</script>
Fr this to work your FirmPassForum action should not be decorated with the [ChildActionOnly] attribute:
public ActionResult FirmPassForum(int eventId)
{
MyViewModel model = ...
return PartialView(model);
}

You can use this also
`//var url = '#Url.Action("ActionName", "Controller")';
$.post("/Controller/ActionName?para1=" + data, function (result) {
$("#" + data).html(result);
............. Your code
});`

Related

How to pass an actionlink's results to a partialview placeholder?

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);
}
});

How to perform the following ajax request on jQuery Accordion?

I've created a jQuery Accordion using Asp.Net MVC, and it's working fine. The accordion displays a list of employee names, and when I click on an item, it shows the details. I'd like to send an AJAX request to get the employee details when they click on an item, instead of loading all the employee details at once. Please look at my code below.
Also, please tell me how to keep the first item in the accordion collapsed instead of showing the details, and is there any way to move the heading a bit to the right without using &nbsp?
<div id="accordion">
#foreach (var item in Model.Employees)
{
<h3> #item.EmployeeName</h3>
<div id = "accordiondiv">
<p>Address: #item.Address</p>
<p>Town: #item.Town</p>
<p>Postcode: #item.PostCode</p>
<p>PhoneNumber: #item.PhoneNumber</p>
</div>
}
</div>
<script>
$(function () {
$("Accordion").click(function (evt) {
$.ajax({
url: "/Accordion/GetEmployeeDetails",
type: 'POST',
data:
//need code to pass the employeeid that was clicked on the accordion,
success: function (data) {
$.each(data, function (i, val) {
//need code to populate the respective accordion with the employee details
});
}
});
}
});
</script>
Here's a sample to send an AJAX request to the controller:
<div id="accordion">
#foreach (var item in Model.Employees)
{
<h3> #item.EmployeeName</h3>
<div id = "accordiondiv" data-id="#item.EmployeeId">
<p>Address: #item.Address</p>
<p>Town: #item.Town</p>
<p>Postcode: #item.PostCode</p>
<p>PhoneNumber: #item.PhoneNumber</p>
<p><input type="button" id="Accordion" class="btn" name="Accordion" /></p>
</div>
}
</div>
<script>
$(function () {
$(".btn").each(function (){
var button = $(this);
var parentDiv = button.parent();
var employeeId = parentDiv.attr("data-id");
button.click(function (){
$.ajax({
url: "/Accordion/GetEmployeeDetails",
type: 'POST',
data: { employeeId : employeeId},
success: function (data) {
$.each(data, function (i, val) {
//need code to populate the respective accordion with the employee details
});
}
});
});
});
</script>
And in your controller:
[HttpGet]
public ActionResult GetEmployeeDetails(int employeeId)
{
// code: get the details based on employeeId
var detail = new Model.EmployeeDetail();
return Json(detail, JsonRequestBehavior.AllowGet);
}
Thiago's implementation seems like it should work. However, I would create a partial view _EmployeeDetails with how you want the details to look, based on the Employee model,
#model Employee
<p>Address: #item.Address</p>
<p>Town: #item.Town</p>
<p>Postcode: #item.PostCode</p>
<p>PhoneNumber: #item.PhoneNumber</p>
In your controller you'll return it as such,
public ActionResult GetEmployeeDetails(int employeeId)
{
...
var employee = Repository.GetEmployee(employeeId);
return PartialView("_EmployeeDetails", employee);
}
Which result you can use to the set the content of each <div id="accordionDiv"> on the AJAX response,
<script>
$(function () {
$(".btn").each(function (){
var button = $(this);
var parentDiv = button.parent();
var employeeId = parentDiv.attr("data-id");
button.click(function (){
$.ajax({
url: #Url.Action("GetEmployeeDetails"),
type: 'POST',
data: { employeeId : employeeId },
success: function (data) { parentDiv.html(data); }
});
});
});
</script>

Load PartialView with using jquery Ajax?

PartialView
#model OsosYeni23072012.Models.TblMeters
<h3>
Model.customer_name
</h3>
<h3>
Model.meter_name
</h3>
Controller
[HttpGet]
public ActionResult MeterInfoPartial(string meter_id)
{
int _meter_id = Int32.Parse(meter_id);
var _meter = entity.TblMeters.Where(x => x.sno == _meter_id).FirstOrDefault();
return PartialView("MeterInfoPartial", _meter);
}
Razor
#Html.DropDownList("sno", new SelectList(Model, "sno", "meter_name"), "-- Select Meter --", new { id = "meters"})
#Html.Partial("MeterInfoPartial")
I want to load partial view, if dropdownlist change. But I dont know How can I do this. I cant find any example about this. I do this with actionlink. But I did not with dropdown before.
controller parameter meter_id equals dropdownlist selectedvalue.
Thanks.
You could subscribe to the .change() event of the dropdown and then trigger an AJAX request:
<script type="text/javascript">
$(function() {
$('#meters').change(function() {
var meterId = $(this).val();
if (meterId && meterId != '') {
$.ajax({
url: '#Url.Action("MeterInfoPartial")',
type: 'GET',
cache: false,
data: { meter_id: meterId }
}).done(function(result) {
$('#container').html(result);
});
}
});
});
</script>
and then you would wrap the partial with a div given an id:
<div id="container">
#Html.Partial("MeterInfoPartial")
</div>
Also why are you parsing in your controller action, leave this to the model binder:
[HttpGet]
public ActionResult MeterInfoPartial(int meter_id)
{
var meter = entity.TblMeters.FirstOrDefault(x => x.sno == meter_id);
return PartialView(meter);
}
Be careful with FirstOrDefault because if it doesn't find a matching record in your database given the meter_id it will return null and your partial will crash when you attempt to access the model.
<script type="text/javascript">
$(function() {
$('#addnews').click(function() {
$.ajax({
url: '#Url.Action("AddNews", "Manage")',
type: 'GET',
cache: false,
}).done(function(result){
$('#containera').html(result);
});
});
});
</script>

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);
}
}

Rendering image(stream object) using jquery

Just wondering, how can I bind an image (stream) returned by an action method in an ajax call to an image element using jquery.
JavaScript:
$(document).ready($(function () {
$(':input').change(function () {
// object
var Person = {
Name: 'Scott',
Address: 'Redmond'
};
// Function for invoking the action method and binding the stream back
ShowImage(Person);
});
}));
function ShowImage(Person) {
$.ajax({
url: '/Person/GetPersonImage',
type: "Post",
data: JSON.stringify(Person),
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
// idImgPerson is the id of the image tag
$('#idImgPerson')
.attr("src", data);
},
error: function () {
alert('Error');
}
});
Action method:
public FileContentResult GetPersonImage(Person person)
{
// Get the image
byte[] myByte = SomeCompnent.GetPersonImage(person);
return File(myByte, "image/png");
}
Problem:
The Action method is returning the stream, but it is not getting rendered on the page.
I am I missing some thing here...
Thanks for looking in to it.
So I was working on this today and ran into your question, which helped (and hurt) me. Here is what I found:
Like Eben mentioned you cant have the json data type. but thats only part of the problem. When you try to $('#idImgPerson').attr("src", data); as in your code you will just set the src attribute to the bytes returned by the call do the GetPersonImage() method.
I ended up using a partial view:
Using the standard mvc3 template
Index.cshtml (excerpt):
<h3>Using jquery ajax with partial views</h3>
<div id="JqueryAjax">
<input class="myButton" data-url='#Url.Action("GetImagesPartial","Home")' name="Button1" type="button" value="button" />
Create the partial view which makes reference to the action that provides the image:
#model string
<div>
<img id="penguinsImgActionJquery" alt="Image Missing" width="100" height="100"
src="#Url.Action("GetPersonImage", "Home", new { someString=Model })" />
<br />
<label>#Model</label>
</div>
HomeController with both action methods:
public ActionResult GetImagesPartial(string someImageName)
{
return PartialView((object)someImageName);
}
public FileContentResult GetPersonImage(string someString)
{
var file = System.Web.HttpContext.Current.Server.MapPath(localImagesPath + "Penguins.jpg");
var finfo = new FileInfo(file);
byte[] myByte = Utilities.FileManagement.FileManager.GetByteArrayFromFile(finfo);
return File(myByte, "image/png");
}
Jquery:
$(document).ready(function () {
$('.myButton').click(function (e) {
var bleh = $(this).attr("data-url");
e.preventDefault();
someData.runAjaxGet(bleh);
});
var someData = {
someValue: "value",
counter: 1,
};
someData.runAjaxGet = function (url) {
_someData = this;
$.ajax({
url: url,
type: "Get",
data: { someImageName: "ImageFromJQueryAjaxName" + _someData.counter },
success: function (data) {
$('#JqueryAjax').append(data);
_someData.counter = _someData.counter + 1;
},
error: function (req, status) {
alert(req.readyState + " " + req.status + " " + req.responseText);
}
});
};
});
sorry I know there is a little bit of extra code in the script file i was trying to play with namespaces too. Anyhow, i guess the idea is you request the partial view with ajax, which contains the image rather than requesting the image directly.

Resources