MVC 5 view not autoupdating partial view - asp.net-mvc

I have a controller
public class AccountDetailsController : Controller
{
private readonly IAccountStatsRepository _accountStatsRepository;
public AccountDetailsController(IAccountStatsRepository accountStatsRepository)
{
_accountStatsRepository = accountStatsRepository;
}
public ActionResult Details(string accountEmail)
{
var stats = _accountStatsRepository.Get(accountEmail);
var accountDetailsViewModel = new AccountDetailsViewModel
{
Email = accountEmail,
Money = stats.TotalCredits
};
return View(accountDetailsViewModel);
}
[OutputCache(NoStore = true, Location = OutputCacheLocation.Client, Duration = 3)] // every 3 sec
public ActionResult GetLatestLogging(string email)
{
//if (email == null || email != null)
//{
var list = new List<LogViewModel>();
return PartialView("LatestLoggingView", list);
//}
}
}
And a View
#using FutWebFrontend.ViewModels
#model AccountDetailsViewModel
#{
ViewBag.Title = "Details";
}
<h2>#Model.Email</h2>
<div>
<h4>Account details</h4>
Money #String.Format("{0:0,0}", Model.Money)
</div>
<div id="loggingstream">
#Html.Partial("LatestLoggingView", new List<LogViewModel>())
</div>
<hr />
<dl class="dl-horizontal"></dl>
<p>
#Html.ActionLink("Back to List", "index", "AccountControl")
</p>
<script type="text/javascript">
$(function() {
setInterval(function () { $('#loggingstream').load('/AccountDetails/GetLatestLogging/#Model.Email'); }, 3000);
});
</script>
But when I go to my page and put a breakpoint in GetLatestLogging then nothing happens
If I hit F12 in chrome I get "Uncaught ReferenceError: $ is not defined "Details:67
From what I can gather, this should hit my Get method every 3 seconds, but I must have made a simple error somewhere

Try this
$( document ).ready(function() {
setInterval(function () {$('#loggingstream').load('/AccountDetails/GetLatestLogging/#Model.Email'); }, 3000);
});

Related

how to get ID from URL in asp.net MVC controller

I want to get the ID from URL in ASP.NET MVC Controller and insert it into Project_ID, the bellow is my code, i tried but its now working for me.
http://localhost:20487/ProjectComponent/Index/1
My Controller
[HttpPost]
public JsonResult SaveComponent(OrderVM O, int id)
{
bool status = false;
if (ModelState.IsValid)
{
using (Entities db = new Entities())
{
ProjComponent ProjComponent = new ProjComponent { project_id = id, title = O.title, description = O.description };
foreach (var i in O.ProjComponentActivities)
{
ProjComponent.ProjComponentActivity.Add(i);
}
db.ProjComponents.Add(ProjComponent);
db.SaveChanges();
status = true;
}
}
}
You can always use a hidden field and update it by jquery/javscript and send it to back end in ajax helper.....
Make sure 1.name should be exactly name as ActionMethod param and 3.Jquery ,jQuery Validate and jQuery unobstrusive ajax is loaded correctly
My code .cshtml
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<div>
#{
AjaxOptions options = new AjaxOptions();
options.HttpMethod = "POST";
options.OnBegin = "OnBeginRequest";
options.OnSuccess = "OnSuccessRequest";
options.OnComplete = "OnCompleteRequest";
options.OnFailure = "OnFailureRequest";
// options.Confirm = "Do you want to Add Country ?";
options.UpdateTargetId = "divResponse";
options.InsertionMode = InsertionMode.InsertAfter;
}
#using (Ajax.BeginForm("AjaxSend", "Stackoverflow", options))
{
<input type="hidden" name="project_id" id="project_id" value="project_id" />
<input type="submit" value="Click me" />
}
</div>
<div id="divResponse">
</div>
<script>
$(function() {
var url = window.location.href;
var array = url.split('/');
var lastsegment = array[array.length - 1];
console.log(lastsegment);
$('#project_id').val(lastsegment);
});
function OnBeginRequest() {
console.log('On Begin');
}
function OnCompleteRequest() {
console.log('On Completed');
}
function OnSuccessRequest() {
console.log('On Success');
}
function OnFailureRequest() {
console.log('On Failure');
}
</script>
and Controller
[HttpPost]
public JsonResult AjaxSend(String project_id)
{
//rest goes here
return Json(new { Success = true });
}
this link may help link
you can get the id from URL Like This:
Cotroller:
public ActionResult Index(int id)
{
ViewBag.ID = id;
Your Code......
return View(...);
}
View:
#{
ViewBag.Title = "Index";
var ID = ViewBag.ID;
}
Now you have an ID in the variable

Showing items in the same page after selecting from a dropdown control

I have a controller with an Index action which returns a ViewModel and a GetCategories action which should return a partial view.
So here is my CategoryController.cs file:
public class CategoryController : Controller
{
public ActionResult Index()
{
CategoryViewModel ob = new CategoryViewModel();
ob.LoadLanguages();
return View(ob);
}
public ActionResult GetCategories(int langID)
{
CategoryViewModel ol = new CategoryViewModel();
ol.LoadCategoriesByLanguage(langID);
if (Request.IsAjaxRequest())
return PartialView("GetCategories",ol);
In my Index.cshtml view I create a dropdown list and, when the user selects an element, it makes an Ajax request to the getCategories action and on success I should load the GetCategories partial view. The problem is that it redirects me to a new page and I can no longer see my dropdown.
Here is my Index.cshtml file:
#model Onion.Web.ViewModels.CategoryViewModel
<script>
$(document).ready(function () {
$("#ddlLanguages").change(function () {
$.ajax({
type: 'GET',
url: '#Url.Action("GetCategories")' + '?langId=' + this.value,
data: {},
success: callbackFuntion('#Url.Action("GetCategories")' + '?langId=' + this.value),
error: function () { alert('Error'); }
});
});
});
function callbackFuntion(url){
window.location = url;
}
</script>
#Html.DropDownList("Languages", new SelectList(Model.lstLanguages, "LanguageID", "Name"), "SELCT LANGUAGE----->",new { id = "ddlLanguages" })
}
And here is my Category.cshtml file:
#model Onion.Web.ViewModels.CategoryViewModel
<table>
<tr>
<td>ID</td>
<td>Title</td>
</tr>
#foreach (var item in Model.lstCategoryLanguages)
{
<tr>
<td>#item.Title</td>
<td>#item.ShortDescription</td>
</tr>
}
</table>
I can't beleve how easy it is in web forms and here i'm struggling for hours. Is there a better way to do all this. Thank you in advance
I slightly modified your Models and made it working prototype, from here you can get the concept and apply it to your models -
Models -
public class CategoryViewModel
{
public List<string> DDLItems { get; set; }
}
public class CategoryNewViewModel
{
public string Name { get; set; }
}
Controller -
public class MyPartialController : Controller
{
public ActionResult Index()
{
CategoryViewModel ob = new CategoryViewModel();
ob.DDLItems = new List<string>();
ob.DDLItems.Add("1");
ob.DDLItems.Add("2");
ob.DDLItems.Add("3");
return View(ob);
}
public ActionResult GetCategories(int langID)
{
CategoryNewViewModel ol = new CategoryNewViewModel();
if (langID == 1)
ol.Name = "One";
else if (langID == 2)
ol.Name = "two";
else
ol.Name = "three";
return PartialView("GetCategories", ol);
}
}
Index View -
#model MVC.Controllers.CategoryViewModel
#{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function () {
$("#DDLCategories").change(function () {
$.ajax({
type: 'GET',
url: '#Url.Action("GetCategories")',
data: {langID : $('#DDLCategories').val()},
success: function (result) { $('#container').html(result); },
error: function () { alert('Error'); }
});
});
});
</script>
<h2>Index</h2>
#Html.DropDownList("DDLCategories", new SelectList(Model.DDLItems), "--Choose any Item--")
<div id="container"> </div>
GetCategories Partial View -
#model MVC.Controllers.CategoryNewViewModel
#Model.Name
When you select a item in Dropdownlist, then the corresponding partialview will be loaded in the div.
Output -
It's normal because you execute a redirection in your success callback.
You can use load function of jQuery to load your partial view in a div of your dom.
<div id="categoriesPlace"></div>
<script>
$(document).ready(function () {
$("#ddlLanguages").change(function () {
$("#categoriesPlace").load('#Url.Action("GetCategories")' + '?langId=' + this.value, function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
alert( msg + xhr.status + " " + xhr.statusText );
}
}
});
});
</script>

How do I Show/Hide partial view based on result I get from service call using jQuery AJAX in MVC4?

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.

Can't pass selected value DropDownListFor to javascript function

My simpel test Model:
public class MovieModel {
public string SelectedCategorieID { get; set; }
public List<CategorieModel> Categories { get; set; }
public MovieModel() {
this.SelectedCategorieID = "0";
this.Categories = new List<CategorieModel>() {new CategorieModel {ID = 1,
Name = "Drama"},
new CategorieModel {ID = 2,
Name = "Scifi"}};
}
}
public class CategorieModel {
public int ID { get; set; }
public string Name { get; set; }
}
My Home controller action Index:
public ActionResult Index() {
Models.MovieModel mm = new Models.MovieModel();
return View(mm);
}
My strongly typed View:
#model MvcDropDownList.Models.MovieModel
#{
ViewBag.Title = "Home Page";
}
<script type="text/javascript">
function categoryChosen(selectedCatID) {
// debugger;
var url = "Home/CategoryChosen?SelectedCategorieID=" + selectedCatID;
$.post(url, function (data) {
$("#minicart").html(data);
});
}
</script>
#using (Html.BeginForm("CategoryChosen", "Home", FormMethod.Get)) {
<fieldset>
Movie Type
#Html.DropDownListFor(m => m.SelectedCategorieID, new SelectList(Model.Categories, "ID", "Name", Model.SelectedCategorieID), "---Select categorie---")
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
}
<input type="button" value="Minicart test" onclick="categoryChosen('#Model.SelectedCategorieID');" />
<div id="minicart">
#Html.Partial("Information")
</div>
Please ignore the first input, because I'm using the second input with 'Minicart test' on it (the HTML.Beginform is there to learn something else later). The mini cart stuff is from another tutorial, I apologize. Don't let it distract you please.
When the button is clicked categoryChosen jQuery is called, which calls the action:
[AcceptVerbs("POST")]
public ActionResult CategoryChosen(string SelectedCategorieID) {
ViewBag.messageString = SelectedCategorieID;
return PartialView("Information");
}
The partial view Information looks like this:
#{
ViewBag.Title = "Information";
}
<h2>Information</h2>
<h2>You selected: #ViewBag.messageString</h2>
My question is why is Model.SelectCategorieID zero (Model.SelectCategorieID = 0) even after I changed the value in the dropdownlist? What am I doing wrong? Thank you very much in advance for answering. If you need any information or anything in unclear, please let me know.
My question is why is Model.SelectCategorieID zero
(Model.SelectCategorieID = 0) even after I changed the value in the
dropdownlist?
That's because you have hardcoded that value in your onclick handler:
onclick="categoryChosen('#Model.SelectedCategorieID');"
If you want to do that properly you should read the value from the dropdown list:
onclick="categoryChosen(this);"
and then modify your categoryChosen function:
<script type="text/javascript">
function categoryChosen(ddl) {
// debugger;
var url = 'Home/CategoryChosen';
$.post(url, { selectedCategorieID: $(ddl).val() }, function (data) {
$('#minicart').html(data);
});
}
</script>
Also I would recommend you using an URL helper to generate the url to invoke instead of hardcoding it in your javascript function. And last but not least, I would recommend you doing this unobtrusively, so that you could put this in a separate javascript file and stop mixing markup and script.
So here's how your code will look like after taking into consideration my remarks:
#model MvcDropDownList.Models.MovieModel
#{
ViewBag.Title = "Home Page";
}
#using (Html.BeginForm("CategoryChosen", "Home", FormMethod.Get))
{
<fieldset>
Movie Type
#Html.DropDownListFor(
m => m.SelectedCategorieID,
new SelectList(Model.Categories, "ID", "Name"),
"---Select categorie---",
new {
id = "categoryDdl"
data_url = Url.Action("CategoryChoosen", "Home")
}
)
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
}
<input type="button" value="Minicart test" id="minicart-button" />
<div id="minicart">
#Html.Partial("Information")
</div>
and then in your separate javascript file unobtrusively subscribe to the click handler of your button and send the AJAX request:
$(function() {
$('#minicart-button').click(function() {
// debugger;
var $categoryDdl = $('#categoryDdl');
var selectedCategorieID = $categoryDdl.val();
var url = $categoryDdl.data('url');
$.post(url, { selectedCategorieID: selectedCategorieID }, function (data) {
$('#minicart').html(data);
});
});
});
Provide an id for your dropdownlist:
#Html.DropDownListFor(m => m.SelectedCategorieID, new SelectList(Model.Categories, "ID",
"Name", Model.SelectedCategorieID), new {id = "myDropDownList"})
And your javascript function as follows:
<script type="text/javascript">
function categoryChosen() {
var cat = $("#myDropDownList").val();
var url = "Home/CategoryChosen?SelectedCategorieID=" + cat;
$.post(url, function (data) {
$("#minicart").html(data);
});
}
</script>
Why your code did not work?
onclick="categoryChosen('#Model.SelectedCategorieID')
is generated as
onclick="categoryChosen('0')
because the value of SelectedCategorieID is 0 when it is generated.

mvc c# with jquery getjson not closing the modal popup but redirects to another page with json result

So I'm not sure what's happening here. I have this modal popup that loads a partial view from an action (this might be the problem??) . The partial view loads perfectly and processes fine but once the post ends and should return a json, instead of the modal just closing and then posting the results it redirects me to another page that shows the json results (not the partial view). I'm not entirely sure if the way i'm approaching this is correct. I just need to close the dialog after the action was successfully processed and then return a message if it has either saved the transaction or throw an error.
Any advice is appreciated. thanks!!!
<script type="text/javascript">
$(function () {
$('#modal-link').click(function () {
var href = this.href;
$('#load-modal-dialog').dialog({
modal: true,
open: function (event, ui) {
$(this).load(href, function (result) {
$('#new-registration').submit(function () {
$.getJSON(href, function (data) {
if (data.success == true) {
$('#messages').html('woo!');
} else {
$('#messages').html('dafuq');
}
this.dialog('close');
});
});
});
}
});
return false;
});
});
</script>
my partial view that gets loaded on the popup
<% using (Html.BeginForm("New", "Registration", FormMethod.Post, new { id = "new-registration" })){ %>
<h2>Register Participant:</h2>
<div class="">
<%: Html.ValidationSummary(null, new { #class = "" })%>
<div class="">
<div class="">Email Address:</div>
<div class="">
<%: Html.TextBox("Email", null, new { #class = "" })%>
</div>
</div>
<button type="submit" value="Submit">Register</button>
</div>
<% } %>
the action
public ActionResult New(){
return PartialView(context.Contest.FirstOrDefault(e => e.Id == 1));
}
[HttpPost]
public ActionResult New(FormCollection formCollection)
{
string email = formCollection["Email"].ToString();
try
{
if (email == "")
throw new Exception("Please provide an email address.");
Registration registration = new Registration
{
ContestId = 1,
Email = email
};
context.Registration.Add(registration);
context.SaveChanges();
return Json(new { success = "true", message = "User succesfully registered to Contest." });
}
catch (Exception ex)
{
//throw ex;
return Json(new { success = "false", message = ex.Message });
}
}
You need to prevent the default action of the link(Opening a new window).Add these lines to your code,
$('#modal-link').click(function (event) {
//....All content..
event.preventDefault();// this will stop the opening new page
event.stopPropergation();
return false;
});

Resources