How can i get data on change event of dropdownlist in MVC4? - asp.net

Hi i am using partial view in mvc. i put dropdown in partial view and render that partial view in index page.
I have to get data on change event of dropdown list.I prefer angularjs instead of java script.but i am not able to call controller Action from view using angularjs.
In Controller:
public class HomeController : AthController
{
public ActionResult Index()
{
var dashboardList = GetAllDashboards() as List<DashboardDefinition>;
return View(dashboardList);
}
public ActionResult GetDashboard()
{
return View();
}
...
...
}
In View:
#model IEnumerable<Portal.Domain.ReportingModule.ReportDefinition.DashboardDefinition>
#{
ViewBag.Title = "Reporting";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Reporting View</h2>
#Html.ActionLink("Add new Chart", "Create", "Chart", new { area = "Reporting" }, null)
#section SubMenu{
#Html.Partial("_ReportingMenu")
}
In PartialView:
#model IEnumerable<Portal.Domain.ReportingModule.ReportDefinition.DashboardDefinition>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<div data-ng-app="">
<div class="nav navbar navbar-default navbar-no-margin submenu" data-ng-controller="dashboardController">
<select class="btn btn-default" id="drpDashboard" data-ng-model="dashboard" data-ng-change="dashboardChange(dashboard)">
#foreach (var dashboard in #Model)
{
<option value="#dashboard.Id">#dashboard.DashboardName</option>
}
</select>
<a id="SubMenuIntegratorNew" class="btn btn-default submenu-item" href="#">
<i class="fa fa-file-o fa-lg"></i>
<span class="submenu-item-text">New</span>
</a>
<a id="SubMenuIntegratorSave" class="btn btn-default submenu-item" href="#">
<i class="fa fa-floppy-o fa-lg"></i>
<span class="submenu-item-text">Save</span>
</a>
<a id="SubMenuIntegratorSaveAs" class="btn btn-default submenu-item" href="#">
<i class="fa fa-files-o fa-lg"></i>
<span class="submenu-item-text">Save As</span>
</a>
<a id="SubMenuIntegratorAddChart" class="btn btn-default submenu-item" href="#">
<i class="fa fa-picture-o fa-lg"></i>
<span class="submenu-item-text">Add Chart</span>
</a>
</div>
</div>
<script type="text/javascript">
function dashboardController($scope) {
$scope.dashboardChange = function (item) {
$http({
url: "/Home/GetDashboard",
method: "GET"
});
}
}
</script>
In this code i checked using debauging that dashboardChage metho is calling but GetDashboard action can't be call.

You can put the Drop down inside a form and include the change attribute to this dropdown like this
#{ Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }); }
#Html.DropDownList("Id", ViewData["Id"] as List<SelectListItem>, new { onchange = "this.form.submit();" })
#{ Html.EndForm(); }

Related

how to fix delete record using partial view?

I want to delete the record from the table with modal but the partial view is not displayed in modal ...
How can I solve this problem !?
And that I can not use onClick !!!
this action for delete in controller:
public IActionResult DelPlatform(int? id)
{
if (id == null)
{
return NotFound();
}
PR_Platform platformModel = _Iunit.PlatformsRepository.GenGetById(id);
if (platformModel == null)
{
return NotFound();
}
return View(platformModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult DelPlatform(int id)
{
_Iunit.PlatformsRepository.GenDeleteById(id);
return RedirectToAction(nameof(PlatformList));
}
this delete button in index view:
<a asp-controller="Platform" asp-action="DelPlatform" asp-route-id="#item.PlatformId" class="btn btn-danger btn-sm waves-effect waves-light" data-toggle="modal" data-target="#delete-modal"><i class="mdi mdi-delete" data-toggle="tooltip" data-placement="top" title="حذف"></i></a>
this script for delete:
<script>
(function ($) {
function Delete() {
var $this = this;
function initilizeModel() {
$("#delete-modal").on('show.bs.modal', function (e) {
}).on('hidden.bs.modal', function (e) {
$(this).removeData('bs.modal');
});
}
$this.init = function () {
initilizeModel();
}
}
$(function () {
var self = new Delete();
self.init();
})
}(jQuery))
</script>
this modal (in shared folder):
<div class="modal fade bs-example-modal-center" tabindex="-1" role="dialog" id="delete-modal" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header text-danger">
<h5 class="modal-title mt-0 text-white"><strong>حذف از پایگاه داده</strong></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-footer mr-auto">
<button type="submit" class="btn btn-primary waves-effect waves-light">حذف شود</button>
</div>
</div>
</div>
this delete action view (for get record name):
#model PR_Platform
#{
Layout = null;
}
<form asp-controller="Platform" asp-action="DelPlatform" method="post">
<div class="modal-body" id="delete-modal">
<p><strong>آیا از حذف <em>"#Model.PlatformName"</em> مطمئن هستید؟</strong></p>
<p class="mb-0"><small>#Model.PlatformName از پایگاه داده حذف خواهد شد</small></p>
</div>
</form>
Please try this:
View:
#{
ViewData["Title"] = "Home Page";
}
<div class="modal fade bs-example-modal-center" tabindex="-1" role="dialog" id="delete-modal" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header text-danger">
<h5 class="modal-title mt-0 text-white"><strong>حذف از پایگاه داده</strong></h5>
<form asp-controller="Platform" asp-action="DelPlatform" method="post">
<div class="modal-body" id="delete-modal">
#*<em>"#Model.PlatformName"</em> <small>#Model.PlatformName از پایگاه داده حذف خواهد شد</small>*#
<p><strong>آیا از حذف مطمئن هستید؟</strong></p>
<p class="mb-0"></p>
</div>
<button type="submit">Click if you are sure to Delete</button>
</form>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#*<div class="modal-footer mr-auto">
<button type="submit" class="btn btn-primary waves-effect waves-light">حذف شود</button>
</div>*#
</div>
</div>
</div>
#*asp-controller="Home" asp-action="DelPlatform" asp-route-id="#item.PlatformId"*#
<a class="btn btn-danger btn-sm waves-effect waves-light" data-toggle="modal" data-target="#delete-modal">Click to Delete<i class="mdi mdi-delete" data-toggle="tooltip" data-placement="top" title="حذف"></i></a>
Here is a whole working demo you could follow:
Model:
public class PR_Platform
{
public int PlatformId { get; set; }
public string PlatformName { get; set; }
}
Main View(Index.cshtml):
Add data-id in the anchor tag for getting the clicked value.
#model IEnumerable<PR_Platform>
#foreach(var item in Model)
{
<a asp-controller="Platform" asp-action="DelPlatform" asp-route-id="#item.PlatformId" data-id="#item.PlatformId" class="btn btn-danger btn-sm waves-effect waves-light" data-toggle="modal" data-target="#delete-modal"><i class="mdi mdi-delete" data-toggle="tooltip" data-placement="top" title="حذف"></i></a>
<a asp-controller="Platform" asp-action="DelPlatform" asp-route-id="#item.PlatformId" data-id="#item.PlatformId" class="btn btn-danger btn-sm waves-effect waves-light" data-toggle="modal" data-target="#delete-modal"><i class="mdi mdi-delete" data-toggle="tooltip" data-placement="top" title="حذف"></i></a>
}
<div class="modal fade bs-example-modal-center" tabindex="-1" role="dialog" id="delete-modal" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header text-danger">
<h5 class="modal-title mt-0 text-white"><strong>حذف از پایگاه داده</strong></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
//add this......
</div>
<div class="modal-footer mr-auto">
<button type="submit" class="btn btn-primary waves-effect waves-light">حذف شود</button>
</div>
</div>
</div>
</div>
JS in main view:
#section Scripts
{
<script>
(function ($) {
function Delete() {
var $this = this;
function initilizeModel() {
$("#delete-modal").on('show.bs.modal', function (e) {
var $button = $(e.relatedTarget); //Button that triggered the modal
var id = $button.data("id"); //get the id
alert(id);
$.ajax({
type: "GET",
url: "/Platform/DelPlatform/"+id,
contentType: "application/json",
success: function (data) {
$(".modal-body").html(data);//load the response html code to the modal
},
error: function (e) {
alert('Error');
}
})
}).on('hidden.bs.modal', function (e) {
$(this).removeData('bs.modal');
});
}
$this.init = function () {
initilizeModel();
}
}
$(function () {
var self = new Delete();
self.init();
})
}(jQuery))
</script>
}
Controller:
public IActionResult DelPlatform(int? id)
{
if (id == null)
{
return NotFound();
}
PR_Platform platformModel = _Iunit.PlatformsRepository.GenGetById(id);
if (platformModel == null)
{
return NotFound();
}
return View(platformModel);
}

When model is not valid, return to partial view inside a view, with error message using asp.net core

I´ve got a modal boostrap. I want to show the error of validation on boostrap modal. But when I leave the model empty and click on submit button Its just viewed as a standalone page.
Partial view:
#model WebApplication1.Models.Book
<form asp-controller="Home" asp-action="AddBook"
data-ajax="true" data-ajax-method="POST" data-ajax-mode="replace" data-ajax-update="#frmaddbook">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Header of Modal</h4>
</div>
<div class="modal-body form-horizontal" id="frmaddbook ">
<span class="alert-danger">
#Html.ValidationSummary()
</span>
<div class="row">
<div class="form-group">
<label asp-for="BookName" class="col-lg-3 col-sm-3 control-label"></label>
<div class="col-lg-6">
<input asp-for="BookName" class="form-control" />
<span asp-validation-for="BookName" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="BookDescription" class="col-lg-3 col-sm-3 control-label"></label>
<div class="col-lg-6">
<input asp-for="BookDescription" class="form-control" />
<span asp-validation-for="BookDescription" class="text-danger"></span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" value="Submit" />
</div>
Index View :
<div class="panel panel-primary">
<div class="panel-body">
<div class="btn-group">
<a class="btn btn-primary marginbutoon" id="showBookgroup" data-toggle="modal" asp-action="AddBook"
data-target="#modal-book">
<i class="glyphicon glyphicon-plus"></i>
Add Book
</a>
</div>
</div>
i use this libraries at top of index view:
jquery.unobtrusive-ajax.min.js
jquery.validate.unobtrusive.min.js
and use at the bottom of index view:
<script src="~/js/book-index.js"></script>
book-index.js:
(function ($) {
function Home() {
var $this = this;
function initilizeModel() {
$("#modal-book").on('loaded.bs.modal', function (e) {
}).on('hidden.bs.modal', function (e) {
$(this).removeData('bs.modal');
});
}
$this.init = function () {
initilizeModel();
}
}
$(function () {
var self = new Home();
self.init();
})
}(jQuery))
Controller:
[HttpGet]
public IActionResult AddBook()
{
var b = new Book();
return PartialView("_AddBook", b);
}
[HttpPost]
[ValidateAntiForgeryToken]
//[HandleError]//not in core
public IActionResult AddBook(Book model)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
return PartialView("_AddBook", model);
}
Model :
public class Book
{
[Key]
public int BookId { get; set; }
[Display(Name = "Book Name :")]
[Required(ErrorMessage = "Enter Book Name Please ")]
public string BookName { get; set; }
[Display(Name = "Book Description")]
[Required(ErrorMessage = "Enter Book Description Please ")]
public string BookDescription { get; set; }
}
My code is shown above. How can i show validation error in modal partial view ?
You can set the Id of form as the data-ajax-update property value of the form , which is ajaxified. This value will be used as the jQuery selector when the result is received from the ajax call.
#model Book
<form asp-controller="Home" asp-action="AddBook" id="myform"
data-ajax="true" data-ajax-method="POST"
data-ajax-mode="replace" data-ajax-update="#myform">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Add Book</h4>
</div>
<div class="modal-body form-horizontal" id="frmaddbook ">
<span class="alert-danger">
#Html.ValidationSummary()
</span>
<div class="row">
<div class="form-group">
<label asp-for="BookName" class="col-sm-3 control-label"></label>
<div class="col-lg-6">
<input asp-for="BookName" class="form-control" />
<span asp-validation-for="BookName" class="text-danger"></span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" value="Submit" />
</div>
</form>
Now when you submit the form and model state validation fails, the action method code will return the partial view result with the validation error messages (generated by the validation helpers) and the jquery.unobtrusive-ajax.js library code will replace (because we specified that with data-ajax-mode="replace") the content of the result of the jquery selector #data-ajax-update (the form tag and it's inner contents) with the response coming back from the server.

ASP.NET MVC is it possible to use ajax.beginform inside a partial view?

Layout -> View -> Partial View
In the View:
<div class="col-md-8">
#{Html.RenderPartial("_komentari", commentlist);}
<div class="gap gap-small"></div>
<div class="box bg-gray">
<h3>#Res.commentwrite_title</h3>
#using (Ajax.BeginForm("postcomment", new { propertyid = Model.PublicID }, new AjaxOptions { UpdateTargetId = "commentsarea", HttpMethod = "Post", InsertionMode = InsertionMode.Replace }, null))
{
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label>#Res.commentwrite_content</label>
<textarea id="comment" name="comment" class="form-control" rows="6"></textarea>
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" value='#Res.commentwrite_btn' />
</div>
</div>
</div>
}
</div>
</div>
In the Partial View:
<div id="commentsarea">
<ul class="booking-item-reviews list">
#if (Model != null)
{
foreach (Comment item in Model)
{
<li>
<div class="row">
<div class="col-md-2">
<div class="booking-item-review-person">
<a class="booking-item-review-person-avatar round" href="#">
<img src="/assets/img/70x70.png" alt="Image Alternative text" title="Bubbles" />
</a>
<p class="booking-item-review-person-name">
#if (item.UserId != null)
{
<a href='#Url.Action("details", "user", new { userid = item.User.PublicId })'>#item.User.Username</a>
}
else
{
Anonymous
}
</p>
</div>
</div>
<div class="col-md-10">
<div class="booking-item-review-content">
<p>
#item.Content
</p>
<p class="text-small mt20">#item.DateOnMarket</p>
<p class="booking-item-review-rate">
#using (Ajax.BeginForm("reportcomment", new { comment = item.PublicId }, new AjaxOptions { UpdateTargetId = "reportscount", HttpMethod = "Post", InsertionMode = InsertionMode.Replace }, null))
{
<a id="submit_link" href="#">Spam?</a>
<a class="fa fa-thumbs-o-down box-icon-inline round" href="#"></a>
}
<b id="reportscount" class="text-color">#item.CommentReports.Count</b>
</p>
</div>
</div>
</div>
</li>
}
}
</ul>
</div>
<script>
$(function () {
$('a#submit_link').click(function () {
$(this).closest("form").submit();
});
});
</script>
View
Both scripts for Ajax are always included in the Layout (I'm already using Ajax on other pages too). On the View page, when I add a new comment, it is added in the database and shows the updated list of comments via ajax. Everything works fine.
Partial View
But if I want to report the comment as spam, I have to click on the link inside the Partial View (#submit_link), and after reporting, inside the #reportscount part, I want to show the updated number of reports of that comment. The actionresults returns that number like Content(numberofreports.toString()). It works but I get the number in a blank page?
Thank you very much.
It's better if you don't. The main issue is that, for security reasons, <script> tags are ignored, when HTML is inserted into the DOM. Since the Ajax.* family of helpers work by inserting <script> tags in place, when you return the partial via AJAX, those will not be present. It's better if you only include the HTML contents of the form in the partial, and not the form itself.

ASP MVC : submit button is not working , when using AJAX.ActionLink

can you help on this please :
The submit button is not working in simple ASP MVC page after trying to open the bootstrap modal , using AJAX.ActionLink, but when I try top open directly (without AJAX.ActionLink) it is working and then calling the controller's action at server side : here is the code
Main Page : index.cshtml
#model IEnumerable<TestQuestionsAnswers.Models.Question>
#{
ViewBag.Title = "Index";
}
<script>
function ShowPopup() {
$("#divmodal").attr('data-toggle', 'modal');
$('#divmodal').modal('show');
}
</script>
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
#Ajax.ActionLink("Validate Data!", "Edit1", "Question", new { id = 1 }, new AjaxOptions { UpdateTargetId = "divresponse", OnComplete = "ShowPopup" }, new { #class = "btn btn-info btn-sm" })
</p>
<!-- Modal -->
<div id="divmodal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Question</h4>
</div>
<div class="modal-body">
<div class="container" id="divresponse">Data is here....</div>
<input type="submit" class="btn btn-info" name="btnsubmit" value="Save">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Please Note: from the code above I am using this :
#Ajax.ActionLink("Validate Data!", "Edit1", "Question", new { id = 1 }, new AjaxOptions { UpdateTargetId = "divresponse", OnComplete = "ShowPopup
to open the modal window .
the Edit.chtml:
#model TestQuestionsAnswers.Models.QuestionEditView
#{
ViewBag.Title = "Edit";
}
#using (Html.BeginForm("Save", "Question", FormMethod.Post))
{
<input type="submit" class="btn btn-info" name="btnsubmit" value="Save" >
}
and the controller 's action which supposed to reach is :
[HttpPost]
public ActionResult Save(string btnsubmit, TestQuestionsAnswers.Models.QuestionEditView questedit)
{
if (btnsubmit == "Save")
{
List<Answer> UpdatedAnswers=questedit.Answers;
dbaccess.SaveEditQuestionsBy(questedit);
}
return RedirectToAction("Index");
}
I appreciate your help
I dont know you have installed unobtrusive-ajax package or not
but if not first go to manage nudget package -> search ajax and install Microsoft.jquery.unobtrusive-ajax.js package
then give this reference in your cshtml
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
then put debugger in controller and check whether method is firing or not.

ASP.Net Razor MVC Bootstrap Login Modal Validation

Using Bootstrap in my Razor page, I am opening a modal window:
<div class="container-fluid">
<div class="navbar navbar-fixed-top navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="offcanvas" data-target=".navbar-offcanvas" data-canvas="body">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand pull-right" href="#">
<img src="assets/img/logo-header.png" alt="Alternate Text for Image">
</a>
</div>
<div class="navbar-offcanvas offcanvas navmenu-fixed-left">
<a class="navmenu-brand" href="#">eServices</a>
<ul class="nav nav-justified">
<li>New Here?</li>
<li>Services</li>
<li>Sign In</li>
</ul>
</div>
</div>
</div>
<div class="modal fade" id="modalLogin" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<p>
<h3 class="modal-title" id="myModalLabel">Login to MyApplication</h3>
</p>
</div>
#using (Html.BeginForm("index", "home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { role = "form", #class = "form-horizontal" }))
{
#Html.AntiForgeryToken()
<div class="form-group #Html.ValidationErrorFor(m => m.Username, "has-error has-feedback")">
<div class="col-sm-12">
#Html.FormTextBoxFor(p => p.Username, new { #class = "form-control" })
#if (!Html.IsValid(m => m.Username))
{
<span class="glyphicon glyphicon-remove form-control-feedback"></span>
}
#Html.ValidationMessageFor(m => m.Username, null, new { #class = "help-block" })
</div>
</div>
<div class="form-group #Html.ValidationErrorFor(m => m.Password, "has-error has-feedback")">
<div class="col-sm-12">
#Html.FormPasswordFor(p => p.Password, new { #class = "form-control" })
#if (!Html.IsValid(m => m.Password))
{
<span class="glyphicon glyphicon-remove form-control-feedback"></span>
}
#Html.ValidationMessageFor(m => m.Password, null, new { #class = "help-block" })
</div>
</div>
#Html.ValidationSummary(true, string.Empty, new { #class = "test" }, "span")
<div class=" pull-right">
<p>
<button type="submit" class="btn btn-default">#Forms.ButtonSignin</button>
</p>
<br />
<p>
#Html.ActionLink("Forgot your username?", "ForgotUsername")
</p>
<p>
#Html.ActionLink("Forgot your password?", "ForgotPassword")
</p>
</div>
}
</div>
</div>
</div>
The issue I have is that, for example, I entered an incorrect username/password combination, the form validates, but the modal window closes. Is there a way to re-open the modal window after the form has posted if the validation triggered an error?
You could add a property named IsModalShown i.e.
public class AModel
{
public bool IsModalShown { get; set; }
}
Render this as a hidden for in your view i.e.
#Html.HiddenFor(m => m.IsModalShown)
When the modal is opened set the hidden value to true, this will enable the modal state to be posted back to the controller action i.e.
$('#modalLogin').on('show.bs.modal', function (e) {
$('#IsModalShown').val(true);
})
Please note the above will depend on the version of bootstrap you are using but there are other docs on the official site
Then add the following to your view that automatically pops it up
$(function(){
#if(Model.IsModalShown)
{
$('#signin_modal').modal('show');
}
});
I had a similar problem, but didn't have a model in view. Posting my solution, in case it would help someone. I wanted to show an error message stored in TempData (in case of wrong login/password combination, on which Batuta was asking).
Controller:
public ActionResult SignIn(string login, string password)
{
if (Membership.ValidateUser(login, password))
{
// something
}
else
{
TempData["message-error"] = "Wrong combination";
}
return RedirectToAction("Index", "Home");
}
Showing the message in modal window:
#if (TempData["message-error"] != null)
{
#TempData["message-error"]
}
Opening modal in index:
#if (TempData["message-error"] != null)
{
<script type="text/javascript">
$('#myModal').modal('show');
</script>
}
Maybe not that clean, but works for me.

Resources