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>
Related
What was I doing wrong?
My method is called twice.
First time I get Id and it's correct behavior
Second time I get Null
I can't get it what is correct way to solve it?
My View
<div class="container">
<div class="row">
#foreach (var item in Model)
{
<div class="col-md-4">
<div class="card" style="width: 18rem;">
<img src="~/Content/not-found-image.jpg" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">#item.Name</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<div id="textButton">
<a class="btn btn-primary" data-index="#item.Id" name="link">Go to anywhere</a>
</div>
</div>
</div>
</div>
}
</div>
</div>
My Controller
[HttpGet]
public ActionResult ListCoach(int id)
{
if (id != null)
{
var ChoachList = _TraningService.Coach(id);
return View(ChoachList);
}
return HttpNotFound();
}
Script
I use script on My View use helper #Section {}
#section scripts {
#*<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>*#
<script>
function PassToContoller(data) {
//alert(data);
$.ajax({
type: "GET",
url: '/TrainingType/ListCoach',
data: { id: data },
success: function (data) {
console.log(data);
window.location.href = '/TrainingType/ListCoach';
return data;
},
error: function () {
$("#loader").fadeOut("slow");
console.log("error1");
}
});
}
$(document).ready(function () {
$("a[name=link]").on("click", function () {
var valueOfClickedTag = $(this).data("index");
alert("Clicked: " + valueOfClickedTag);
var callFunc = PassToContoller(valueOfClickedTag)
});
$(":button[id=GoToAnywhere3]").on("click", function () {
var valueOfClickedBtn = $(this).data("index");
var callFunc = PassToContoller(valueOfClickedBtn)
});
});
</script>
}
if I use the method:
I can't get into View ListCoach
Can I return Json on My View?
[HttpGet]
public JsonResult ListCoach(int id)
{
var ChoachList = _TraningService.Coach(id);
return Json(ChoachList,JsonRequestBehavior.AllowGet);
}
Your code seems to be OK and in theory, your action should not call twice but I want to show you some ways in order to catch the problem:
when a call is made to the server in chrome developer tools in the tab network you will see a record in which there is a column named Initiator that shows you the call is created by who and where.
you can use keyword DEBUG in the first of function PassToContoller and look at the stack to know who one call your function
and about your final question, my answer is negative and you can not use this way to pass JSON object to your view but you can pass JSON object beside model by ViewBag or ViewData
In your function PassToContoller,in ajax success,you use window.location.href = '/TrainingType/ListCoach';,so after you call the function,it will have two requests,one with ajax,one with window.location.href.
If you want to get jsondata in ajax,you need to use dataType: "json", in ajax.
Here is a demo to pass json data:
Action:
[HttpGet]
public JsonResult GetJson(int id)
{
return new JsonResult(new TestModel { Id=id,Name="Test"});
}
View:
<button onclick="test()">
test
</button>
#section scripts
{
<script>
function test() {
$.ajax({
type: "GET",
url: 'GetJson',
data: { id: 1 },
dataType: "json",
success: function (data) {
console.log(data);
},
error: function () {
$("#loader").fadeOut("slow");
console.log("error1");
}
});
}
</script>
}
result:
Update:
You can try to use a form to pass Id to action(without using <a></a>):
<form asp-action="GetJson" asp-route-id="#item.Id">
<input type="submit" value="Go to anywhere" />
</form>
Action:
[HttpGet]
public IActionResult GetJson(int id)
{
return View("Index",new List<TestModel> { new TestModel { Id = id, Name = "Test" } });
}
I am new to ASP.NET and web development of any kind. I have searched for many hours for a solution to my problem, but I can't seem to get my partial view to show up in the div.
What is happening is the view is showing up, but it's replacing the entire page instead of showing up in the div within the main page.
My controller looks something like this:
public class MyController
{
public ActionResult ShowView(int id)
{
// get view model from id
return PartialView(viewModel);
}
}
My Main View looks something like this
#model List<viewModelType>
<div>
#foreach (var item in Model)
{
<div>
#Html.ActionLink(item.Name, "ShowView", new { id = item.ID }, new { #class = "btn-sm" })
</div>
}
</div>
<div>
// here is where I want to partial view to go!
</div>
This is what the partial view looks like:
#model viewModelType
<div>Model.DataToDisplay</div>
Would this work for you?
[ChildActionOnly]
public class MyController
{
public ActionResult ShowView(int id)
{
// get view model from id
return PartialView(viewModel);
}
}
And in your view:
<div>
// here is where I want to partial view to go!
#Html.Action("ShowView")
</div>
Okay I figured it out with Christos' help.
The main view should look like this:
#model List<viewModelType>
<div>
#foreach (var item in Model)
{
<div>
<button class="js-showViewBtn" data-itemId=#item.ID>item.Name</button>
</div>
}
</div>
<div class="js-show-view">
// here is where I want to partial view to go!
</div>
<script type="text/javascript">
$(function () {
$('.js-showViewBtn').click(function (e) {
e.preventDefault();
var itemId = $(this).data("itemId");
$.ajax({
method: "GET",
url: "/MyController/ShowView",
data: { id: itemId },
cache: false
}).success(function(data){
$('.js-show-view').html(data);
});
})
});
</script>
For some reason the id of the item was not being returned, so I tried it like this and it worked. Hope this helps others too.
Thanks for your help Christos.
You need a bit of JavaScript to do that you want. Basically, you have to wire up a click event handler for your links and when the user click on one of them an ajax request would be triggered.
#model List<viewModelType>
<div>
#foreach (var item in Model)
{
<div>
#Html.ActionLink(item.Name, "ShowView", new { id = item.ID }, new { #class = "btn-sm js-show-view-btn" })
</div>
}
</div>
<div class="js-show-view">
// here is where I want to partial view to go!
</div>
<!-- Before the following script been loaded, he jQuery should have been loaded -->
<script>
$(function(){
$(".js-show-view-btn").click(function(e){
e.preventDefault();
$.ajax({
method: "GET",
url: "/MyController/ShowView",
data: { id = $(e).id },
cache: false
}).success(function(data)
{
$(".js-show-view").html(data);
});
})
});
</script>
I want to have a page where I can enter loan number then I will call a WCF get service to see if a loan number is valid. If loan# is valid, I want to show loan related data (partial view) on the same page.
Here is my main View:
#model LoanStatus.Web.Models.Validate
#{
ViewBag.Title = "Validate";
}
#section Scripts {
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
}
<script type="text/javascript">
jQuery(function ($) {
$("#txtssn").mask("9999");
});
function validateRequest() {
var $form = $('form');
if ($form.valid()) {
$.support.cors = true;
var lnkey = $('#txtlnkey').val();
$.ajax({
type: "GET",
url: "http://localhost:54662/Service1/ValidateRequest/" + encodeURIComponent(lnkey),
contentType: "application/json; charset=utf-8",
dataType: "json", //jsonp?
success: function (response) {
$('#Result').html('Loading....');
if (response.ValidateRequestResult.toString().toUpperCase() == 'TRUE') {
alert('validated');
} else {
alert('cannot validated' + response.ValidateRequestResult.toString().toUpperCase());
//$("#Result").hide();
}
$('#Result').html(response.ValidateRequestResult);
//alert(response.ValidateRequestResult.toString());
},
error: function (errormsg) {
alert("ERROR! \n" + JSON.stringify(errormsg));
}
});
//
} else {
$('#Result').html('Input Validation failed');
}
}
</script>
#using (Html.BeginForm()) {
<fieldset>
<legend>Log in Form</legend>
<ol>
<li>
#Html.LabelFor(m => m.LoanKey, new{})
#Html.TextBoxFor(m => m.LoanKey, new { #id = "txtlnkey" })
#Html.ValidationMessageFor(m => m.LoanKey)
</li>
</ol>
<input type="button" value="Get Status" onclick="javascript:validateRequest();" />
</fieldset>
}
<div id="Result">
#if (ViewBag.Validated)
{
#Html.Action("GetLoanInfo");
}
</div>
Below is my controller:
namespace LoanStatus.Web.Controllers
{
public class ValidateController : Controller
{
//
// GET: /Validate/
[HttpGet]
public ActionResult Index()
{
var model = new Validate() {LoanKey = "", Last4Ssn = ""};
ViewBag.Validated = false;
return View(model);
}
[HttpPost]
public ActionResult Index(Validate model, bool validated)
{
// do login stuff
ViewBag.Loankey = model.LoanKey;
ViewBag.Validated = true;
return View(model);
}
public ActionResult GetLoanInfo() // SHOWs Search REsult
{
return PartialView("_LoanInfoPartial", ViewBag.Loankey);
}
}
}
I want to have '#Html.Action("GetLoanInfo");' rendered only if jQuery AJAX service call returns TRUE (Where I have alert('validated'). I am not sure how to do that. My issue can be resolved if I can set value to ViewBag.Validated in success:function(). But based on what I read, it cannot be set in jQuery.
I tried $("#Result").hide(); and $("#Result").show(); but it did not work. Please help.
Can you try with this:
In your function validateRequest() ajax success, at the place where you are showing alert('validated'); use this and try:
$('#Result').load('#Url.Action("GetLoanInfo", "Validate")');
In your view make Result div empty
<div id="Result"> </div>
Tell me if it helps.
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
});`
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  ?
<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>