Showing items in the same page after selecting from a dropdown control - asp.net-mvc

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>

Related

Couldn't Load the data on Dropdown menu using Asp.net Mvc Json

i am creating a simple inventory control system using Asp.net Mvc Json.when i am tring to load the category data.category Data is not loaded to the Dropdown menu. code which i tried so far i attached below along with the screen shot image.
enter image description here
Form design
<div class="card-action">
<div class="form-group">
<label class="form-label">Category</label>
<select class="form-control" id="category" name="category"
placeholder="Category" required>
<option value="">Please Select</option>
</select>
</div>
</div>
Jquery
getCategory();
function getCategory() {
$.ajax({
type: 'GET',
url: '/product/Getcategory',
dataType: 'JSON',
success: function (data) {
console.log(data);
for (var i = 0; i < data.length; i++) {
$('#category').append($("<option/>", {
value: data[i].id,
text: data[i].cat_name,
}));
}
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
}
Controller
public class ProductController : Controller
{
aspoEntities db = new aspoEntities();
// GET: /Product/
public ActionResult Index()
{
return View();
}
public ActionResult Getcategory()
{
using (aspoEntities db = new aspoEntities())
{
var category = db.categories.ToList();
return Json(new { data = category }, JsonRequestBehavior.AllowGet);
}
}
}
Change your controller to
public class ProductController : Controller
{
// GET: /Product/
public ActionResult Index()
{
return View();
}
public ActionResult Getcategory()
{
aspoEntities db = new aspoEntities()
var category = db.categories.ToList();
return Json(category, JsonRequestBehavior.AllowGet);
}
}
It seems your db context has been disposed before the json is being serialized.
Try to inject the db context to your controller and get rid of the using statement.
Or move your return statement outside the using block.

How to Get HTML drop down list value from View to controller in MVC?

Small help required
1) I have created an html Dropdown in MVC view like this
<select name="Associateddl" id="Associateddl"></select>
2)I am appending the options to the dropdownlist using Jquery Ajax like
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'customservice.asmx/getallmember',
dataType: 'JSON',
success: function (response) {
var getData = JSON.parse(response.d);
console.log(getData.length);
if (getData.length > 0) {
$("#msg").hide();
$.each(getData, function (i, item) {
var optiontext = "";
optiontext = "<option value='" + item.Aid + "'>" + item.AMail + "</option>";
$("#Associateddl").append(optiontext);
});
}
else {
$("#msg").append("<p style='color:red'><b>Currently there are no members ,Please Add !!</b></p>");
}
},
error: function (err) {
//alert(err);
}
});
3)Now i want to retrive the dropdown selected value to controller from View.
My Model:
public class Event
{
[DisplayName("Event Name")]
[Required(ErrorMessage ="Event Name is Mandatory...")]
public string Eventname { get; set; }
[DisplayName("Event Year")]
[Required(ErrorMessage ="Enter the Year...")]
public int Year { get; set; }
[DisplayName("Associate ID")]
[Required(ErrorMessage ="Associate ID is required...")]
public string Associateddl { get; set; }
}
My Controller:
[HttpPost]
public ActionResult Index(Event eve)
{
string ename = eve.Eventname;
int eyr = eve.Year;
string eassociate = eve.Associateddl; //Here i want to retrive the dropdownselected Value
return View();
}
Please help me to get the Html dropdown seleted value to Controller from View.
Here is an example on how you can see the value of the ddl in the controller. I will get you an ASP.NET Fiddle you can click on that will host the solution.
web service
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string getallmember()
{
var drop2 = new List<SelectListItem>();
SelectListItem sli1 = new SelectListItem { Text = "MoreOptions1", Value = "1" };
SelectListItem sli2 = new SelectListItem { Text = "MoreOptions2", Value = "2" };
drop2.Add(sli1);
drop2.Add(sli2);
//GET NewtonSoft
var json = JsonConvert.SerializeObject(drop2);
return json;
}
Controller
public class HomeController : Controller
{
[HttpPost]
public ActionResult Tut118(string Associateddl)
{
//put breakpoint here
return View();
}
public ActionResult Tut118()
{
return View();
}
View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut118</title>
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
$("#theButton").click(function () {
$.ajax({
type: "Post",
url: "customservice.asmx/getallmember",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#Associateddl").empty();
var theData = JSON.parse(response.d);
$.each(theData, function (i, anObj) {
$("#Associateddl").append($('<option>').text(anObj.Text).attr('value', anObj.Value));
});
}
,
error: function (request, status, error) {
alert(error);
}
});
})
})
</script>
</head>
<body>
<div>
#using (Html.BeginForm())
{
<input type="button" id="theButton" value="click to get ddl" />
<select name="Associateddl" id="Associateddl"></select>
<input type="submit" value="click after selecting ddl" />
}
</div>
</body>
</html>

MVC 5 view not autoupdating partial view

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

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.

ASP.NET MVC 3 AJAX request returns 404 Not Found error

Here's my code (question found below):
VIEW
// This function is called by another function when radioButtonGroup.change().
var requestValues = function (form) {
var option = form.find("input:radio:checked").attr("value");
// This seemingly shows the correct url for the action method desired.
alert("Form Action: " + form[0].action + "\nForm Method: " + form[0].method);
if (form.valid()) {
$.ajax({
url: form[0].action,
type: form[0].method,
data: option,
success: function (result) {
alert("Had success.");
$('#createForm').replaceWith(result);
},
error: function (xhr) {
alert("An error occurred: " + xhr.status + " " + xhr.statusText);
}
});
}
return false;
}
...(other code here)...
#using (Html.BeginForm("CreateForm", "MyController", FormMethod.Post,
new { #id = "optionForm" }))
{
<div id="options">
#foreach (MyOption op in Model.GetOptions()) {
<div class="editor-field">
#Html.RadioButton("formOption", op.OptionType, false,
new { #id = op.ID, #title = #op.Description })
<label for="#op.ID">#op.Name</label>
</div>
}
</div>
<input type="submit" value="Select" style="display:none;" />
}
CONTROLLER
[HttpPost]
public PartialViewResult CreateForm(MyOptionType formOption) {
MyViewModel model = new MyViewModel();
model.ApplyOptionValues(formOption);
return PartialView("_CreateForm", model);
}
REGISTER ROUTES
// Default
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
My issue is that when I click a radio button, the AJAX request executes but I get a "404 Not Found" error (even though the alert in the jQuery function seems to show the appropriate url). I spent all day yesterday on this, and I cannot figure out what the heck is wrong. I'm running ASP.NET MVC 3 app on IIS Express, and I'm not using Areas (that I know of anyway). Anyone have any suggestions on how to fix this? Thanks.
EDIT
The alert box shows the following message:
Form Action: https://localhost:44300/MyController/CreateForm
Form Method: post
EDIT
Here is an entire test view and test controller that recreates the error:
VIEW
<h2>TestAction</h2>
<script type="text/javascript">
$(document).ready(function () {
$("#optionForm input[name='radioOption']").change(function () {
requestValues($(this).closest("form"));
});
var requestValues = function (form) {
var option = form.find("input:radio:checked").attr("value");
alert("Form Action: " + form[0].action + "\nForm Method: " + form[0].method);
if (form.valid()) {
$.ajax({
url: form[0].action,
type: form[0].method,
data: option,
success: function (result) {
alert("AJAX success.");
//$('#createForm').replaceWith(result);
},
error: function (xhr) {
alert("An error occurred: " + xhr.status + " " + xhr.statusText);
}
});
}
return false;
}
});
</script>
#using (Html.BeginForm("CreateForm", "Test", FormMethod.Post, new { #id = "optionForm" })) {
#Html.RadioButton("radioOption", "value1", false, new { #id = "radioButton1" })
<label for="radioButton1">Radio Button 1</label>
#Html.RadioButton("radioOption", "value2", false, new { #id = "radioButton2" })
<label for="radioButton2">Radio Button 2</label>
#Html.RadioButton("radioOption", "value3", false, new { #id = "radioButton3" })
<label for="radioButton3">Radio Button 3</label>
<input type="submit" value="Select" style="display:none;" />
}
<div id="createForm"></div>
CONTROLLER
public class TestController : Controller {
public ActionResult TestAction() {
return View();
}
[HttpPost]
public ActionResult CreateForm(string option) {
return View("TestAction");
}
}
#using (Html.BeginForm("CreateForm", "MyController", FormMethod.Post, new { id = "optionForm" }))
should be:
#using (Html.BeginForm("CreateForm", "My", FormMethod.Post, new { id = "optionForm" }))
Remember that in ASP.NET MVC helpers you should not pass the Controller suffix. It is assumed.
So the correct url should be:
https://localhost:44300/My/CreateForm
and not:
https://localhost:44300/MyController/CreateForm
where you obviously have the MyController class:
public class MyController: Controller
{
public ActionResult CreateForm(MyOptionType formOption)
{
...
}
}

Resources