Refresh DIV using partial view in MVC5 - asp.net-mvc

I am trying to refresh a div based on the dropdown selection. I have a main view which uses a partial view (_Module). The main view has a dropdown; upon selecting the dropdown I am trying to change the content in the partial view which in turn would be reflected on the main view.
The main view:
#model Test.Models.CreateDirectoryModel
#{
ViewBag.Title = "CreateAdmin";
}
#using (Html.BeginForm("CreateAdmin", "RDBWeb", FormMethod.Post))
{
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#ProductType").change(function () {
var catType = $(this).val();
$("#result").load('#(Url.Action("GetPPOFlag", "RDBWeb", null, Request.Url.Scheme))?catType=' + catType);
});
});
</script>
#Html.ValidationSummary(true)
<div class="form-horizontal">
<h4>Create a New Directory</h4>
<hr />
<div class="form-group">
#Html.LabelFor(model => model.DirectoryNumber, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DirectoryNumber)
#Html.ValidationMessageFor(model => model.DirectoryNumber)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductType, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ProductType, new SelectList(Model.ProductType), "Select Product")
#Html.ValidationMessageFor(model => model.ProductType)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DirectoryName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DirectoryName)
#Html.ValidationMessageFor(model => model.DirectoryName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.AdminName, ViewBag.Drop as SelectList, "Select Admin")
#Html.ValidationMessageFor(model => model.AdminName)
</div>
</div>
<div id="result">
#if(Model.Module != null)
{
{Html.RenderPartial("_Module", Model.Module);}
}
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
<div>
</div>
</div>
}
The partial view is:
#model Test.Models.CreateDirectoryModel
#foreach (string s in Model.Module)
{
#Html.LabelFor(a => s.ToString());
}
The methods relevant for these in the controller are:
public ActionResult GetPPOFlag(string catType)
{
ProdTypeModel p1 = new ProdTypeModel();
int flag = p1.GetPPOFlag(catType);
return RedirectToAction("GetModule", new { flag = flag });
}
[HttpGet]
public ActionResult GetModule(int flag)
{
ModuleType m1 = new ModuleType();
List<string> moduleList= m1.GetModules(flag);
return PartialView("_Module", moduleList);
}
My problem is that by default the Partial view object is null initially as the dropdown value is yet to be chosen. I added a check to render the partial view only if the object is not null; but that does not load the new values into the partial view. All I see is that the GetModule method is invoked and the partial view method is called as well, but there is no change in the div on the main page nor the partial view.

try to do like this, just keep an empty div inside in the main view like this
<div id="result">
</div>
On dropdown selection change, give a ajax call and get partial view and render html in the div
$('#result').empty();
$("#result").html(data);

Related

ASP.NET MVC - A potentially dangerous Request.Form value was detected from the client

Am trying to click save button to update what I have in text editor using ckeditor but I got this error
A potentially dangerous Request.Form value was detected from the client (OPTION_VALUE="Welcome to the Na...").
The controller is shown below
Controller
public ActionResult EditRegistrationGuideline(long id)
{
OPTIONS options = _optionsService.GetOption(id);
return View(options);
}
//
// POST: /Product/Edit/5
[HttpPost]
public ActionResult EditRegistrationGuideline(long id, OPTIONS options)
{
try
{
// TODO: Add update logic here
if (ModelState.IsValid)
{
options.OPTION_ID = id;
options.ACTION_STATUS = 0;
options.CREATED_DATE = DateTime.Now;
_optionsService.AddOption(options);
return RedirectToAction("Index");
}
}
catch
{
//return View();
ModelState.AddModelError("", "We cannot edit this Option. Verify your data entries !");
}
return View();
}
and the view is here
View
#{
//ViewBag.Title = "CreateRegistrationGuideline";
}
<div class="content-header clearfix">
<h1 class="pull-left">
<i class="fa fa-plus"> </i> Edit Registration Guideline
</h1>
<div class="col-xs-3 pull-right">
<input type="button" class="btn btn-block btn-warning" value="Back" onclick="location.href='#Url.Action("IndexRegistrationGuideline", "Options")'" />
</div>
<div class=" box box-body box-primary">
#using (Html.BeginForm("EditRegistrationGuideline", "Options", FormMethod.Post, new { #class = "form-horizontal", #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#*<h4>OPTIONS</h4>
<hr />*#
#*#Html.ValidationSummary(true)*#
#Html.ValidationSummary(false, null, new { #class = "text-danger" })
<div class="row .col">
<div style="margin-top:20px" class="mainbox col-md-12 col-md-offset-0 col-sm-8 col-sm-offset-2">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Edit Option</div>
</div>
<div class="panel-body">
#*<div class="form-group">
#Html.LabelFor(model => model.OPTION_NAME, new { #class = "control-label col-md-2" })
<div class="col-md-10">*#
#*#Html.LabelFor(model => model.OPTION_NAME, new { #class = "control-label col-md-2" })
<div class="col-md-10">*#
#*#Html.EditorFor(model => model.OPTION_NAME)*#
#*#Html.HiddenFor(model => model.faculty_activation_date, new { #Value = System.DateTime.Now })*#
#Html.HiddenFor(model => model.OPTION_NAME)
#Html.ValidationMessageFor(model => model.OPTION_NAME)
<div class="form-group">
#*#Html.LabelFor(model => model.OPTION_VALUE, new { #class = "control-label col-md-2" })*#
<div class="col-md-10">
#Html.LabelFor(model => model.OPTION_VALUE, "Option Value")
#*<textarea class="form-control" placeholder="Enter Option Value" name="OPTION_VALUE" id="editor1"></textarea>*#
#Html.TextAreaFor(model => model.OPTION_VALUE, new { #class = "form-control", #id = "editor1" })
#Html.ValidationMessageFor(model => model.OPTION_VALUE, "", new { #class = "text-danger" })
</div>
</div>
#*<div>
#Html.LabelFor(model => model.OPTION_VALUE, "Option Value")
#Html.TextAreaFor(model => model.OPTION_VALUE, new { #type = "textarea", #id="editor1", #class = "form-control", #placeholder = "Enter Option Value", #autocomplete = "on" })
#Html.ValidationMessageFor(model => model.OPTION_VALUE, null, new { #class = "text-danger" })
</div>*#
#*<div class="form-group">
#Html.LabelFor(model => model.ACTION_STATUS, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ACTION_STATUS)
#Html.ValidationMessageFor(model => model.ACTION_STATUS)
</div>
</div>*#
</div>
<div class="panel-footer">
<div class="panel-title">
<div class="form-actions no-color">
<input type="submit" value="Save" class="btn btn-success" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
#*<div>
#Html.ActionLink("Back to List", "Index")
</div>*#
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="https://cdn.ckeditor.com/4.5.7/standard/ckeditor.js"></script>
<script>
$(function () {
CKEDITOR.replace('editor1');
});
</script>
}
Please what do I do.
I use CKEDITOR
XSS error ("A potentially dangerous Request.Form value was detected from the client(...)").
Solution:
[ValidateInput(false)]
Differnce b/w them
AllowHtml:
The AllowHtml attribute can be applied to a Model property and it will disable the validation by ASP.Net MVC only for that particular property
Advantages
The AllowHtml attribute is developed for Model class.
The Scope is limited to specific property of the Model class.
It is the safe and recommended solution.
ValidateInput
The ValidateInput attribute can be applied to a Controller’s Action method and it will disable the validation by ASP.Net MVC only for that particular Action method.
Advantages
The Scope is limited to specific Action method of the Controller class.
If you have multiple properties accepting HTML content, then this method will reduce redundancy.
When Model class is not used for designing Form elements then this attribute is needed.For complete details Link
Just place ValidateInput(false) attribute on controller's action.
[HttpPost]
[ValidateInput(false)]
public ActionResult EditRegistrationGuideline(long id, OPTIONS options)
The other option is to place [AllowHtml] attribute on Model Property, have a look on SO post to get difference between them
ValidateInput(false) vs AllowHtml
I was experiencing a similar issue with the following error message A potentially dangerous Request.Form value was detected from the client.
As an alternative to the previous answers, I found encoding the value passed back to the controller worked. CKEditor allows you to do this by setting the config config.htmlEncodeOutput = true;.
The documentation for this can be found at: https://docs-old.ckeditor.com/ckeditor_api/symbols/CKEDITOR.config.html#.htmlEncodeOutput
I got this error while testing XSS on my site.
This is a very good feature that the model gives us that prevents XSS, CSRF from penetrating your site.
Do not disable it as much as possible.

MVC, Normal partial view and List partial view. not working together!!! S.O.S. xD

I have a view that contains 2 partial views.
#model ListViewModel
....
#{
Html.RenderPartial("EditCartItemsPartical");
Html.RenderPartial("ShowProductINFO", Model.Products);
}
and I just want to create a from with the first partial, and a list with the second.
The partial views
EditCartItemsPartical.cshtml
#model TestNewATM3._0.Models.CartItem
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(model => model.CartId, "CartId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CartId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CartId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductId, "ProductId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ProductId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductId, "", new { #class = "text-danger" })
</div>
</div>
.... // more control for CartItem
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
ShowProductINFO.cshtml
#model IEnumerable<TestNewATM3._0.Models.AllProduct2>
<p>#Html.ActionLink("Create New", "Create")</p>
<table class="table">
<tr>
<th>ID</th>
<th>#Html.DisplayNameFor(model => model.Title)</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>#Html.DisplayFor(model => item.Id)</td>
<td>#Html.DisplayFor(modelItem => item.Title)</td>
</tr>
}
</table>
And in my controller I got this.
public ActionResult Edit()
{
var db = ApplicationDbContext.Create();
var list = new ListViewModel
{
Products = db.AllProduct2s.ToList(),
Users = db.Users.ToList(),
Cart = db.Carts.ToList(),
CartItem = db.CartItems.ToList()
};
return View(list);
}
But the problem is that I cant show both partial at the same time because if I send the list in my view, then my first partial gets a problem cause it want a #model TestNewATM3.0.Models.CartItem. but if I don't sent the list My list wont show because I don't send it.
So how do i show a normal partial form view and a List partial view at the same time?
I'm having a little difficulty understanding your examples (i.e you have an edit view with create buttons), it looks like your trying to create a view to edit the cart.
Note: I would suggest renaming the CartItem property of your model to CartItems for clarity, but I'll use the current property names for the examples below.
You could render the partial view for each of the items in the list like so,
but this approach more is more than a little messy:
foreach(var cartItem in Models.CartItem){
Html.RenderPartial("EditCartItemsPartical", cartItem);
}
A simpler and more performant approach would be to edit the first view so it takes a collection of cart items
Like so
#model IEnumerable<TestNewATM3._0.Models.CartItem>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#foreach(var modelItem in Model.CartItem){
<h4>CartItem</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => modelItem.CartId, "CartId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => modelItem.CartId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => modelItem.CartId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductId, "ProductId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => modelItem.ProductId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => modelItem.ProductId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Aantal, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => modelItem.Aantal, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => modelItem.Aantal, "", new { #class = "text-danger" })
</div>
</div>
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
Of course this will require you to change the server side code to receive a collection of cart items, but from the user's perspective not having to post a form back multiple times, to complete your changes is going to result in a better experience.
disclaimer: I changed the above view in notepad, might need to adjust a bit before it works perfectly
I hope this helps.

searching database and displaying on .cshtml page

I have this code in my controller:
public ActionResult Search(String searchstring)
{
var number = from n in db.UCountInfoes
select n;
if (!String.IsNullOrEmpty(searchstring))
{
number = number.Where(i => i.IDNumber.Equals(searchstring));
}
return View(number);
}
and on my .cshtml page i have this which i use to search:
<div class="form-group">
#Html.LabelFor(model => model.ID_Number, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ID_Number, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ID_Number, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" name="SearchButton" value="Search" class="btn btn-inverse" />
</div>
</div>
After clicking the search button i want to return the records found on another .cshtml page.
return RedirectToAction("Action Name", "Your Controller Name", number);
Instead of return View you can use the above method.
Here Action Name is the View Name you want to show the results into.

ASP MVC jquery validation in bootsrap tabs causes an undesired postback

I have a form with 3 bootstrap tabs in it. Client Validation works correctly when the tab where the validation error occurs is open and submit button is clicked. However, when i switch to a tab with no errors (while having errors in other tabs) a post back occurs and i get the correct validation messages.
Its a minor issue, but post back is not desired in this situation, because full client side validation must be completed before sending request to the server.
How can i correct this behavior?
Below is a copy of my form HTML:
#model RBZPOSMVC.ViewModel.CreateEditItem
....
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#Details">Item Details</a></li>
<li><a data-toggle="tab" href="#Sales">Sale Price Groups</a></li>
<li><a data-toggle="tab" href="#Purchases">Purchase Price Groups</a></li>
</ul>
<div class="tab-content">
<div id="Details" class="tab-pane fade in active">
<div class="form-group">
#Html.LabelFor(model => model.Item.ItemCode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Item.ItemCode, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Item.ItemCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Item.ItemName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Item.ItemName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Item.ItemName, "", new { #class = "text-danger" })
</div>
</div>
.... // more form controls
</div>
<div class="hidden">
#for (var i = 0; i < Model.PriceGroupList.Count; i++)
{
<div class="form-group" id="#Model.PriceGroupList[i].PriceGroupTypeId">
#Html.HiddenFor(model => model.PriceGroupList[i].PriceGroupId)
#Html.LabelFor(model => model.PriceGroupList[i].PriceGroupName,
Model.PriceGroupList[i].PriceGroupName,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PriceGroupList[i].Price, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PriceGroupList[i].Price, "", new { #class = "text-danger" })
</div>
</div>
}
</div>
<div id="Sales" class="tab-pane fade in ">
</div>
<div id="Purchases" class="tab-pane fade in ">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
<script>
$.validator.setDefaults({
ignore: ""
});
</script>
#Scripts.Render("~/bundles/items")
#Scripts.Render("~/bundles/jqueryval")
}
Since two of you tabs are hidden when you submit the form, you need to configure the $.validator to validate hidden elements (which are not validated by default).
You current use of $.validator.setDefaults({ ignore: "" }); is not correct for jquery version 2.2.0 (I believe that usage was depreciated in version 1.9) and it needs to be
$.validator.setDefaults({
ignore: []
});
Note: do not add the above inside $(document).ready()

When pushing a button inside a partial view, parent form is validated

In a MVC 5 application, I have a partial view with a button to submit some information. But when I push that button the parent form is validated, making all the validating errors displayed. All I want is that only the validated fields in the partial view are executed with no interaction with the parent form.
Code update (partial view, UploadFile):
<form action="#Url.Action("Upload","File")" method="post" enctype="multipart/form-data">
<label for="photo">Photo:</label>
<input type="file" name="photo" id="photo" />
<input type="submit" value="Upload" />
</form>
Code parent form:
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CategoriaId, "CategoriaId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CategoriaId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CategoriaId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Titulo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Titulo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Titulo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Descripcion, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Descripcion, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Descripcion, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Precio, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Precio, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Precio, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
#Html.Partial("UploadFile")
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Since you have a <form> tag inside the partial view and you put #Html.Partial("UploadFile") inside #using (Html.BeginForm()) block like below
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
....
....
....
#Html.Partial("UploadFile")
}
It will be rendered as nested forms like this
<h2>Create</h2>
<form>
....
....
....
<form action="/File/Upload" method="post" enctype="multipart/form-data">
<label for="photo">Photo:</label>
<input type="file" name="photo" id="photo" />
<input type="submit" value="Upload" />
</form>
</form>
which is invalid html. You need to move #Html.Partial("UploadFile") outside of #using (Html.BeginForm()) block
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
....
....
....
}
#Html.Partial("UploadFile")
This may cause due to nested form.
Make sure that child form is not nested inside another form.
the HTML specs forbid nested forms.
#using (Html.BeginForm())
{
..
}
#Html.Partial("UploadFile") // place it outside of main form
As partial view contain another form you need to place it outside of main form anotherwise it will be nesting(HTML specs forbid nested forms)

Resources