I have ActionResult method that uses Httpost, but when I debug it does not get in the method, only ends in ActionResult for using HttpGet. What could be the main reason for this? I want to store value back to the database column, at this point it does non of that and have debug as well inspect nothing on the browser.
//GET/Courses-List
[HttpGet]
public ActionResult CoursesRegistration()
{
eNtsaCourses courses = new eNtsaCourses();
//courses.Course = Course;
return View();
}
[Route("Home/CoursesRegistration")]
[HttpPost]
public ActionResult CoursesRegistration([Bind(Include = "Id,Course,Nickname,Term, EnrolledAs, Published")] eNtsaCourses courses)
{
if(ModelState.IsValid)
{
try
{
cb.eNtsaCourse.Add(courses);
cb.SaveChanges();
return Json(new { success = true });
}
catch(Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
}
return PartialView("CoursesRegistration", courses);
}
#using(Html.BeginForm("CoursesRegistration", "Home", FormMethod.Post, new { id="testForm", #class="form-horizontal"})) {
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Start New Course</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="form-group row">
<label for="CourseName" class="col-sm-3 col-form-label">CourseName</label>
<div class="col-sm-5">
#Html.EditorFor(model => model.CourseName, new { htmlAttributes = new { #class = "form-control", autofocus = "autofocus", placeholder = "CourseName" } })
</div>
</div>
<div class="form-group row">
<label for="Content-Licence" class="col-sm-3 col-form-label">Content Licence</label>
<div class="col-sm-5">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
Create Courses
<script type="text/javascript">
$("#exampleModal.btn-success").click(function () {
saveData();
});
function saveData() {
$.ajax({
url: "/Home/CoursesRegistration",
data: $('#testForm').serialize(),
type: 'post',
success: function (data) {
if (data.Success) {
$("#exampleModal").modal('hide');
} else {
}
},
error: function (xhr, status) {
}
});
return false;
}
</script>
</div>
</div>
}
ok a couple of things, why in razor are you using a Html.BeginForm and then overriding that with ajax/js?
Best bet here would be choose one method and use that, my preference would be sticking the whole modal into a partial and using a C# object as the model for that partial, then you can use your beginform without having to mess around with ajax/js and serialisation.
Then you can have a single input of the model in your controller POST function.
Have you checked to see if the button is actually firing the js? I noticed you wired it up to
$("#exampleModal.btn-success").click(function () {
saveData();
});
when it should be
$("#exampleModal .btn-success").click(function () {
saveData();
});
maybe stick some console logs in to check and see if it fires and what the data is prior to sending.
Also change the controller function to a httpget to see if it is finding the route ok, then change back to post and you should know then if it is the controller, the route, or the frontend code. I suspect the frontend code.
$(selector).click(function);
If you are using multiple selector in jquery then take a space between two selector.
You need to use as below
$("#exampleModal .btn-success").click(function () {
saveData();
});
Related
I would like to have this error modal window appear if there are issues or errors that need to be displayed to the user after calling the SaveDailyCriteria action. I need the partial view to be rendered within the view where the SaveDailyCriteria action call is made. With the code that I currently have below, the return PartialView("_ErrorsModal", notification) gets called but is never displayed on my main view.
Controller
[HttpPost]
public ActionResult SaveDailyCriteria(Daily report, string EnteredCriteriaName)
{
var criteria = report.ConvertToCriteria(report);
criteria.CriteriaName = EnteredCriteriaName;
var dr = new ReportDaily();
var nameExists = dr.DoesCriteriaNameAlreadyExist(criteria);
if (dr.SaveReportCriteria(criteria, nameExists, out Notification notification) == false)
{
return PartialView("_ErrorsModal", notification);
}
else {
return View(report);
}
}
Main View
#model Company.Areas.Reports.Models.Daily
#using Company.TaxCollection.Reports;
#{
ViewData["Title"] = "Daily Report";
}
<h1>#ViewData["Title"]</h1>
<br />
#using (Html.BeginForm("DailySubmit", "Reports", FormMethod.Post, new { id = "reportForm", #class = "report-form col-9" }))
{
...
...
<div id="saveModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title float-left">Save Criteria</h4>
<button type="button" class="close" data-dismiss="modal"></button>
</div>
<div class="modal-body">
<label>Enter the name to save as:</label><input type="text" id="savedReportName" name="EnteredCriteriaName" class="form-control" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="saveSubmit" data-dismiss="modal">Save</button>
</div>
</div>
</div>
</div>
}
<script>
$(document).ready(function () {
var dataType = 'application/x-www-form-urlencoded; charset=utf-8';
$(function () {
$('#saveSubmit').on('click', function (evt) {
var data = $('form').serialize();
//Ajax form post
$.ajax({
type: 'POST',
data: data,
contentType: dataType,
url: '#Url.Action("SaveDailyCriteria", "Reports")',
success: function (data) {
console.log(data);
if (data.success) {
//window.location.href = data;
} else {
//window.location.href = data;
}
}
});
});
});
});
</script>
_ErrorsModal Partial View
#model Company.NotificationPattern.Notification
<!-- Modal -->
<div id="errorsModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title float-left">Warning</h4>
<button type="button" class="close" data-dismiss="modal"></button>
</div>
<div class="modal-body">
#if (Model.HasErrors || Model.HasWarnings) {
<p>#Model.GetConcatenatedErrorMessage(Environment.NewLine + Environment.NewLine)</p>
}
</div>
<div class="modal-footer">
<button type="button" id="modalConfirm" class="btn btn-primary" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
You can achieve this various ways, one option:
In your controller post method, return a json when it passes and the partial when it fails.
Within your jquery $.ajax post check for json and proceed otherwise render the result to your modal
In your case, the json returned on pass would indicate the url of the view to redirect to (not the view itself otherwise there's no way to know if it's a new view or the partial error). e.g
if (save() == false)
{
return PartialView("_ErrorsModal", notification);
}
else {
return Json({
success = true,
url = this.Url.Action("SaveDailyCriteria", new { reportId = report.ReportId }
});
}
and your javascript to:
$.ajax({
type: 'POST',
...
success: function (data) {
if (data.success)
window.location.href = data.url;
else
$("#modalId").html(data);
}
});
the alternative is to always return json but render the _ErrorsModal (on error) or View (on success) within the controller to a string and add that string as a json property. IMO better to let the MVC pipeline handle rendering to HTML so recommend the above approach.
I am trying to figure out what is the best way to show a generic error message that can be shown in all of the pages in my app. The error view should be shown when a form POST request is executed.
To make the error view available everywhere I've put it in the _Layout.cshtml but I am not quite sure how show it when I submit a POST request from my form.
Note: the solution should not force the page to refresh (i.e. should be asynchronous).
Right now I am using TempData to store and show the message
This is my _Layout.cshtml
<!DOCTYPE html>
...
<body>
#if (TempData["SystemError"] != null)
{
<div>#TempData["SystemError"]</div>
}
#RenderSection("BodyFill", false)
#RenderBody()
...
#RenderSection("Scripts", required: false)
</body>
</html>
This is my controller action:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ShareWorkbook(string emails, string title, string id, string queryBuilderId)
{
var emailStrArr = Regex.Split(emails, Constants.SplitPattern).ToList();
var workbookShareModel = new WorkbookShareModel
{
Id = id,
QueryBuilderId = queryBuilderId,
Title = title,
Emails = emailStrArr
};
// check to see if the 'WorkbookShareModel' is valid (takes into account its property DataAnnotation)
if (TryValidateModel(workbookShareModel))
{
try
{
ShareWorkbook(workbookShareModel);
}
catch (Exception e)
{
//Todo -- Exception handling
TempData["SystemError"] = Res.System_Error_Message;
}
}
// return no content to avoid page refresh
return NoContent();
}
That is the form (it's in a partial view that is loaded into the index.cshtml)
#using DNAAnalysisCore.Resources
#model DNAAnalysisCore.Models.WorkbookShareModel
#* Partial view that contains the 'Share Workbook dialog' modal *#
<!-- Modal -->
<div onclick="activateShareButtons()" class="modal fade" id="shareFormModal" role="dialog">
<div class="modal-dialog modal-md">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Share Workbook - #Model.Title</h4>
</div>
#using (Html.BeginForm("ShareWorkbook", "Home", FormMethod.Post, new { #id = "partialform" }))
{
<div class="modal-body">
...
<div class="modal-footer">
<button onclick="hideDialog()" type="submit" class="btn btn-primary">Share</button>
<button onclick="activateShareButtons()" id="btnCancelDialog" type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
}
</div>
</div>
</div>
Create a div in _Layout.cshtml
<div id="messageDiv"></div>
Button in the partial view with ValidateButton() function on onclick event
<button onclick="ValidateButton()" id="btnCancelDialog" type="button" class="btn btn-default">Validate</button>
JQuery
function ValidateButton() {
// If you have any parameter
var obj ={
parm: "1"
};
$.ajax({
url: '/Home/ValidationProcess',
contentType: 'application/json; charset=utf-8',
type: 'POST',
data: JSON.stringify(obj),
cache: false,
success: function (result) {
$("#messageDiv").html(result);
},
error: function (xhr, status, error) {
alert("Error");
}
});
}
Controller
public string ValidationProcess(string parm)
{
// Do something
return "Message";
}
Don't forget to add JQuery library
I managed to find a solution using the unobtrusive Ajax html (this stack overflow question helped me - link). I converted my original Html.BeginForm (synchronous) to asyncronous call that refreshes a div when the request is executed:
<form id = "partialform" asp-action="ShareWorkbook" asp-controller="Home" method="post" data-ajax="true" data-ajax-update="divEmp">
<div class="modal-body">
...
<div class="modal-footer">
<button onclick="hideDialog()" type="submit" class="btn btn-primary">Share</button>
<button onclick="activateShareButtons()" id="btnCancelDialog" type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</form>
_Layout.cshtml:
...
<body>
<div id="divEmp">
#if (TempData["error"] != null)
{
<p>#TempData["error"]</p>
}
</div>
#RenderSection("BodyFill", false)
#RenderBody()
...
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ShareWorkbook(string emails, string title, string id, string queryBuilderId)
{
...
TempData["error"] = "TEST ERROR MESSAGE";
// return no content to avoid page refresh
return NoContent();
}
Can please someone help me here?! Thank you!
I have a view that displays a list of products along with an "Add Product" button for each. I am calling the CreateNewProduct method for each "Add Product" click to find the status of the product. Depending on the status, either I need to stay on the same view or I need to call a modal popup. I am able to do this by creating a modal popup in a different view. But I want to call the modal popup div (also pass the modal) from the same view where it displays a list of products. Is this possible?
public ActionResult CreateNewProduct(int productId)
{
var sharedProduct = _productTemplateService.GetSharedProducts(productId);
var _finalSharedProducts = (sharedProduct.Any(t => t.productId != productId));
if (_finalSharedProducts)
{
var sharedProdctTemplate = _productTemplateService.GetSharedProduct(productId);
return View("ModalView", new SharedModel
{
SharedProduct = sharedProdctTemplate
});
}
else
{
_productTemplateService.CreateNewProduct(productId);
return RedirectToAction("Details", "ProductTemplate");
}
}
Model View Code
<div class="modal fade" id="myModal" 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">Shared Product</h4>
</div>
<div class="modal-body">
<div class="flex-row">
<div class="col-6">
<div class="d-flex flex-row">
<div class="p-2">Product ID</div>
<div class="p-2">Product Types</div>
<div class="p-2">Status</div>
</div>
#foreach (var productTemplate in Model.SharedProduct )
{
<div class="d-flex flex-row">
<div class="p-2">#productTemplate.ProductId</div>
<div class="p-2">#productTemplate.ProductType</div>
<div class="p-2">#productTemplate.StatusCode</div>
</div>
}
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<p>
#Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |
#Html.ActionLink("Back to List", "Index")
</p>
<script type="text/javascript">
$(document).ready(function () {
$('#myModal').modal('show');
});
</script>
UPDATE:
I made it working. This is what I did. At the end, I have mentioned issues I am facing.
Link, modal and script in my main view - Detail View (called from ProductTemplate Controller)
<td>Add New Product</td>
<div class="modal fade" id="mymodel" role="dialog" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Shared Products</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body" id="mymodelbody">
</div>
</div>
</div>
<script>
var loadModal = function (productId, customerId) {
$.ajax({
type: 'GET',
url: '/NewProductTemplate/CreateNewProduct',
cache: false,
data: {
productId: productId,
customerId: customerId
},
dataType: 'html',
success: function (data) {;
$("#mymodelbody").html(data);
$("#mymodel").modal("show");
}
});
}
</script>
NewProductTemplateController Code
public ActionResult CreateNewProduct(Guid productId, Guid customerId)
{
var sharedProduct = _productTemplateService.GetSharedProducts(productId);
var _finalSharedProducts = (sharedProduct.Any(t => t.productId != productId));
if (_finalSharedProducts)
{
var sharedProdctTemplate = _productTemplateService.GetSharedProduct(productId);
return PartialView("_shared", new SharedModel
{
SharedProduct = sharedProdctTemplate
});
}
else
{
_productTemplateService.CreateNewProduct(productId);
return RedirectToAction("Details", "ProductTemplate");
}
}
Partial view _shared.view code
#model SharedModel
#using (Html.BeginForm("ShareProduct", "NewProductTemplate", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="flex-row">
<div class="col-6">
<div class="d-flex flex-row">
<div class="p-2">Product ID</div>
<div class="p-2">Product Types</div>
<div class="p-2">Status</div>
</div>
#for (var i = 0; i < Model.SharedProducts.Count(); i++)
{
#Html.HiddenFor(model => model.SharedProducts.ElementAt(i).ProductId)
#Html.HiddenFor(model => model.SharedProducts.ElementAt(i).CustomerId)
#Html.HiddenFor(model => model.SharedProducts.ElementAt(i).ProductType)
#Html.HiddenFor(model => model.SharedProducts.ElementAt(i).StatusCode)
#Html.HiddenFor(model => model.SharedProducts.ElementAt(i).IsShared)
<div class="d-flex flex-row">
<div class="p-2">#Html.DisplayFor(model => model.SharedProducts.ElementAt(i).ProductId)</div>
<div class="p-2">#Html.DisplayFor(model => model.SharedProducts.ElementAt(i).ProductType)</div>
<div class="p-2">#Html.DisplayFor(model => model.SharedProducts.ElementAt(i).StatusCode)</div>
#if (Model.SharedProducts.ElementAt(i).StatusCode == VersionStatus.PUBLISHED)
{
<div class="p-2">#Html.EditorFor(m => m.SharedProducts.ElementAt(i).IsShared)</div>
}
</div>
}
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-sm btn-primary" />
<button type="button" class="btn btn-sm btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
PROBLEM:
1) When I save submit button in modal pop-up (partial view), it calls ShareProduct method from NewProductTemplate controller. For some reason, model SharedModel's SharedProducts property is null when it gets to controller code. Can you please help me here why it gets null?
public ActionResult ShareProduct (SharedModel shareModel)
{
//Access ShareProducts from shareModel
return RedirectToAction("Details", "ProductTemplate");
}
PROBLEM:
2) I want to load popup only if the product is shared, otherwise I just want to redirect to Detail view as mentioned in NewProductTemplate controller's CreateNewProduct method. Problem is that it loads Detail view also in popup if product is not shared since that's what my script is doing. Is there any way that I can check data in Success function before showing modal popup? If data/html contains Shared text, I would like to load the normal Detail view. I am just assuming. I tried to do so but with no success.
Detail method in ProductTemplate Controller
public ActionResult Details()
{
var productTemplate = _productTemplateService.GetAllProducts(User);
return View(new DetailsModel
{
ProductTemplate = productTemplate,
});
}
(This is for Bootstrap 3.3.7 Hopefully it's relevant for the version you're on)
I handle this by popping open the modal on the client side from my main view. The link that pops the modal contains the URL to the controller method that will render the actual contents (list of products, in your case). This controller method should return a partial view.
Modal in my main view:
<div class="modal fade name-of-my-modal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content"></div>
</div>
</div>
Link in my main view:
<a class="btn btn-default btn-xs" data-toggle="modal" data-target=".name-of-my-modal" role="button" href="/SomeController/SomeMethodThatReturnsPartialView/234">Show Modal</a>
My controller method for the partial view:
public ActionResult SomeMethodThatReturnsPartialView(int id)
{
var model = GetProducts();
return PartialView("_IndexPartial", model);
}
My partial view that will populate the actual modal contents:
<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">Title goes here</h4>
</div>
<form class="form-horizontal" id="SomeId" name="SomeName" role="form">
<div class="modal-body">
<div>Product 1</div>
<div>Product 2</div>
<div>Product 3</div>
<div>Product 4</div>
</div>
</form>
Also, if the contents of the modal change frequently, or are variable based upon the ID you pass to the partial controller method, then you'll want to clear the modal contents when closing it. From your main view:
$(document).on('hidden.bs.modal', '.modal', function (e) {
// Handles the event thrown when a modal is hidden
$(this).removeData('bs.modal');
$(this).find(".modal-content").empty();
});
Let me know if this helps, and whether anything needs to be clarified.
Problem 2 you could return a JSON result and put the HTML in a string as shown here:
https://www.codemag.com/article/1312081/Rendering-ASP.NET-MVC-Razor-Views-to-String
you could also set a boolean on the returned JSON for whether to redirect.
If it is a redirect do that in Javascript on the success using
window.location
I have two buttons in a view that call different modal windows ("AgregarProducto") and ("CargarOrden")
Cargar O. de Compra <span class="glyphicon glyphicon-file" aria-hidden="true"></span>
Agregar Producto <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
These are loaded using the following Javascript code:
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(document).ready(function () {
$("body").on("click", "a.dialog-window", null, function (e) {
e.preventDefault();
var $link = $(this);
var title = $link.text();
$('#AgregarProducto.modal-title').html(title);
var url = $(this).attr('href');
if (url.indexOf('#') == 0) {
$('#AgregarProducto').modal('show');
}
else {
$.get(url, function (data) {
$('#AgregarProducto .te').html(data);
$('#AgregarProducto').modal();
}).success(function () { $('input:text:visible:first').focus(); });
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("body").on("click", "a.dialog-window", null, function (e) {
e.preventDefault();
var $link = $(this);
var title = $link.text();
$('#CargarOrden.modal-title').html(title);
var url = $(this).attr('href');
if (url.indexOf('#') == 0) {
$('#CargarOrden').modal('show');
}
else {
$.get(url, function (data) {
$('#CargarOrden .te').html(data);
$('#CargarOrden').modal();
}).success(function () { $('input:text:visible:first').focus(); });
}
});
});
</script>
}
The problem is that clicking on a button loads the window twice! (I attach a photo)
in my controllers I made sure to call a partial type view
[HttpGet]
public ActionResult AgregarProducto()
{
return PartialView();
}
[HttpGet]
public ActionResult CargarOrden()
{
return PartialView();
}
I'm using bootstrap to call my views "AddProduct" and "LoadOrder" from my main view ... my two containers:
div class="modal fade" id="AgregarProducto" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h2 class="modal-title"></h2>
</div>
<div class="modal-body"><div class="te">Espere Porfavor...</div></div>
</div>
</div>
</div>
<div class="modal fade" id="CargarOrden" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h2 class="modal-title"></h2>
</div>
<div class="modal-body"><div class="te">Espere Porfavor...</div></div>
</div>
</div>
</div>
I have never worked with modal windows, what happens? what am I doing wrong? any help for me?
You have 2 scripts, one which opens the AgregarProducto modal, and the one which opens the CargarOrden modal.
Because both scripts are executed when ever you click on a link with class="dialog-window", (which both your links have), then both scripts are executed, and both modals are displayed.
A simple solution is to just give your links an id attribute, say id="cargarorden" for the first link and id="agregarproduct" for the second, then change the scripts to
$('#cargarorden').click(function(e) {
.... // you code that opens the CargarOrden modal
});
$('#agregarproduct').click(function(e) {
.... // you code that opens the AgregarProducto modal
});
Note that since the links are not loaded dynamically, then there is no need to use event delegation using .on().
A better alternative would be to identify the associated modal in the link using a data- attribute so that only one script is required
<a data-dialog="CargarOrden" href="#Url.Action("CargarOrden", "Entradas")" ...>
and then
$('.dialog-window').click(function(e) {
// Get the associated dialog
var dialog = $('#' + $(this).data('dialog'));
....
});
and within that script, use dialog as your selector, i.e.
dialog.find('.modal-title').html(title); // instead of
dialog.modal('show'); // instead of $('#CargarOrden').modal('show');
dialog.find('.te').html(data); // instead of $('#CargarOrden .te').html(data);
In Asp.net mvc 5. we have a login page which implements HTML.BeginForm() to post data to controller , if the username and password are incorrect, we are sending error back to the front end using partial views. Everything work fine, In case of error only error message is displayed on the screen and nothing else.
Controller
[HttpPost]
public ActionResult SingleSSOMPLogin(SSoStateModel model)
{
//Check the Code with SP providers and Authorization server.
if(model.SAMLAssertion.validMPData)
{
return RedirectToAction("SSOServiceMP" , "SAML");
}else
{
//Error message processed.
model.errorMessage = SSOState.SAMLAssertion.errorMessage;
return PartialView("_LoginError" , model);
}
}
The view contain the following Code
<div class="peripheral">
<div class="panel panel-default panel-peripheral">
#{Html.Partial("_LoginError", Model);}
<div class="panel-heading clearfix">Please Log In</div>
<div class="panel-body">
<div class="brand-logo eop-logo">
<script type="text/javascript">
function changeImage() {
document.getElementById("Logo").src = '#Url.Content("~/Content/images/TopLogo.gif")';
}
</script>
<img id="Logo" width="200" src='#Url.Content("~/Content/images/TopLogo.gif")' onerror="changeImage()" />
#{ Html.EnableClientValidation(true);}
<!--Ajax call to Controller-->
#using (Html.BeginForm("SingleSSOMPLogin", "Accounts"))
{
#Html.ValidationSummary(true);
<div id="group-email" class="form-group col-md-12 ">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", placeholder = "Please enter your Email address" })
#Html.ValidationMessageFor(m => m.Email)
</div>
<div id="group-password" class="form-group col-md-12">
#Html.PasswordFor(m => m.Password, new { #class = "form-control", placeholder = "Please enter your password" })
#Html.ValidationMessageFor(m => m.Password)
</div>
<div class="form-group">
<div class="col-md-12">
<button type="submit" class="btn btn-primary pull-left">Login</button>
<a id="forgot" href='#Url.Action("ForgotPassword","Accounts")' class="btn btn-link btn-sm pull-right">Forgot your password?</a>
</div>
</div>
}
</div>
</div>
</div>
</div>
Partial View
#{
Layout = null;
}
#if (Model.Result!= null)
{
<div class="alert alert-warning alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>#Model.Result.errorMessage</strong>
</div>
}
When Error occur, I get redirect to same view again with all query parameter gone and display only error message.
How to solve following issue?
The partial view will return only the fragment you defined.
So when called from a "complete" view with
#{Html.Partial("_LoginError", Model);}
it will generate the corresponding part of the view.
In your situation what is most common is to add a model error and return the complete view (that must have a ValidationSummary section):
[HttpPost]
public ActionResult SingleSSOMPLogin(SSoStateModel model)
{
//Check the Code with SP providers and Authorization server.
if(model.SAMLAssertion.validMPData)
{
return RedirectToAction("SSOServiceMP" , "SAML");
}else
{
//Error message processed.
ModelState.AddModelError("error", SSOState.SAMLAssertion.errorMessage);
return View(model);
}
}
If you want to use the partial view you have to call it from an javacript ajax call and insert the response in your page. With jQuery it is something more or less like:
$.ajax({ url: <partial view url>,
type: 'GET',
success: function (result) {
$(updateSelector).hide().html(result).effect("fade", "fast");
}
});