Validation multiple checkbox form - asp.net-mvc

in the page I have only three checkbox, the client should choose at least one before clicking on the submit button :
Controller :
[HttpPost]
public ActionResult Client(OrderItems model)
{
if (bValidated){
//Code here
}
else
{
model.itemChoosed = false;
return View("Client", model);
}
View Client :
#model WebApp.Models.OrderItems
#using (Html.BeginForm("Client", "Home", FormMethod.Post, new { #class = "form-group", role = "form" }))
{
#Html.AntiForgeryToken();
<h2>Client</h2>
#Html.Partial("SentMessage")
<div>
<div>
<h3>Item 1</h3>
<label>#Html.CheckBoxFor(model => model.CLInfo.Item1) Item 1</label>
</div>
<div>
<h3>Item 2</h3>
<label>#Html.CheckBoxFor(model => model.CLInfo.Item2) Item 2</label>
</div>
<div>
<h3>Item 3</h3>
<label>#Html.CheckBoxFor(model => model.CLInfo.Item3) Item 3</label>
</div>
</div>
<div class="row">
<input type="submit" name="action:Client" id="btnClient" class="btn btn-primary flat btn-large pull-right" value="Client" />
</div>
}
After I choose to put the condition into a Partail View :
Partial View SentMessage:
#model WebApp.Models.OrderItems
#if (!model.itemChoosed)
{
<div>You must choose at least one item</div>
}
I have the error message :
The view 'Client' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/Client.aspx
..
~/Views/Home/Client.cshtml
..
but Home/Client.cshtml existe since it's the view
Thanks

Related

Calling a view from different models in ASP.NET MVC

In my ASP.NET MVC application in the view, I'm calling another view that is not related to the current model. There I need some help that how to call the different model views from another view.
#model Asp_PASMVC.Models.VehicleService
#using Asp_PASMVC.Infrastructure
#{
ViewBag.Title = "View";
Layout = "~/Views/Shared/_Layout.cshtml";
List<SelectListItem> CompanyList = (List<SelectListItem>)TempData.Peek("ComapnyList");
List<SelectListItem> ReqTypes = (List<SelectListItem>)TempData.Peek("RequestTyleList");
List<SelectListItem> Employees = (List<SelectListItem>)TempData.Peek("EmployeeList");
List<SelectListItem> Location = (List<SelectListItem>)TempData.Peek("LocationList");
Asp_PASMVC.Models.AppRequest RequestDetails = (Asp_PASMVC.Models.AppRequest)TempData.Peek("RequestDetails");
}
#{
Html.RenderPartial("_MainRequestView", RequestDetails);
}
#using (Html.BeginForm("WorkshopUpdate", "VehicleService", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.HiddenFor(model => model.Req_Id)
#Html.AntiForgeryToken()
if (Model != null && Model.VehicleServiceApproveDetails != null)
{
foreach (Asp_PASMVC.Models.VehicleServiceApproveDetails Emp in Model.VehicleServiceApproveDetails)
{
Html.RenderPartial("_WorkshopUpdate", Emp);
}
}
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<!-- Default box -->
<div class="card">
<div class="card-header">
<h3 class="card-title">Approver Details</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse" title="Collapse">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<div class="card-body">
<div>
<fieldset id="pnlApproverList" style="display:none">
<legend><h5>To whom you want to send this request for approval ? </h5> </legend>
<br />
<ul id="RequApprover" style="list-style-type: none">
#if (Model != null && Model.ApprovalPartyList != null)
{
foreach (Asp_PASMVC.Models.ApprovalParty Emp in Model.ApprovalPartyList)
{
Html.RenderPartial("_ApprovalView", Emp);
}
}
</ul>
<button type="button" id="addAnotherApprover" class="btn btn-success" href="#" onclick="this.style.display = 'none';">Add</button>
<script type="text/javascript">
$(function () {
// $("#movieEditor").sortable();
$("#addAnotherApprover").click(function () {
$.get('/VehicleService/AddApproverToReq', function (template) {
$("#RequApprover").append(template);
});
});
});
</script>
<br />
</fieldset>
</div>
</div>
<!-- /.card-footer-->
</div>
<!-- /.card -->
</div>
</div>
</div>
</section>
<div class="card-footer">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update and Sent" class="btn btn-success" />
</div>
</div>
</div>
}
<p>
#Html.ActionLink("Back to List", "Index")
</p>
So likewise here the model is VehicleService. So within that view, I want to call another view that is not within the vehicleservice model.
But I cannot load that partial view within this view. Is there any way to do this?
#model Asp_PASMVC.Models.ApprovalParty
#using Asp_PASMVC.Infrastructure
#{
string UserLvel = TempData.Peek("UserLevelClaims").ToString();
}
<li style="padding-bottom:15px">
#using (Html.BeginCollectionItem("ApprovalPartyList"))
{
<div class="row">
<div class="col-md-5 col-sm-5">
<div class="form-group">
<label>
#Html.RadioButtonFor(m => m.Approve_Type, false)
<span class="radiomargin">For Manager</span>
</label>
<br />
#if (UserLvel != "1")
{
<label>
#Html.RadioButtonFor(m => m.Approve_Type, true)
<span class="radiomargin">For Top Manager </span>
</label>
#Html.ValidationMessageFor(model => model.Approve_Type, "", new { #class = "text-danger" })
}
</div>
</div>
</div>
<br />
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="form-group row">
Select the Approver
<div class="col-sm-8">
#Html.DropDownListFor(model => model.Approver_Id, new List<SelectListItem>(), new { #id = "ddlEmployees", #class = "js-dropdown" })
#Html.ValidationMessageFor(model => model.Approver_Id, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
}
</li>
Create a ViewModel which can have both Properties and pass that viewmodel to View
Model class:
public class VehicleSerivceViewModel
{
public VehicleService VehicleService { get; set; }
public ApprovalParty ApprovalParty { get; set; }
}
In View :
#model Asp_PASMVC.Models.VehicleServiceVewModel
pass ViewModel to partial as below:
#Model.ApprovalParty

Multiple forms in one view page

I'm working on an application that handles employee's profile.
I have 3 forms (all in the same controller) in a single view page, but it only saves the 1st form. And when i save the 2nd form, it clears the values of the 1st and 3rd form.
Here is my code:
Views/EMPs/Index:
#using (Html.BeginForm("Edit", "EMPs", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<div class="pull-right">
<input type="submit" value="Update" name="personalsubmit" class="btn btn-success" />
</div>
</div>
}
#{ Html.RenderAction("Index", "EMP_REFERENCE", new { id = Model.eMP.lineno });}
#using (Html.BeginForm("Edit", "EMPs", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<div class="pull-right">
<input type="submit" value="Update" name="jobsubmit" class="btn btn-success" />
</div>
</div>
}
#{ Html.RenderAction("Index", "EMP_BENEFITS", new { id = Model.eMP.lineno });}
#using (Html.BeginForm("Edit", "EMPs", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<div class="pull-right">
<input type="submit" value="Update" name="otherssubmit" class="btn btn-success" />
</div>
</div>
}
EMPsController
public ActionResult Edit([Bind(Include = "lineno,EMPNO,IDNO..")] EMP eMP)
{
if (ModelState.IsValid)
{
if (Request.Form["personalsubmit"] != null)
{
db.Entry(eMP).State = EntityState.Modified;
db.SaveChanges();
}
if (Request.Form["jobsubmit"] != null)
{
db.Entry(eMP).State = EntityState.Modified;
db.SaveChanges();
}
if (Request.Form["otherssubmit"] != null)
{
db.Entry(eMP).State = EntityState.Modified;
db.SaveChanges();
}
return Redirect(Request.UrlReferrer.PathAndQuery);
}
return View(eMP);
}
I couldn't put them all in one form, because i used an ajax beginForm between them for another crud method. Since I've read that nested forms are not recommended.
Is there a way to save one form without it clearing the values of the other forms?
Is there a way to save one form without it clearing the values of the other forms?
You could simply use ajax.beginform for each of those forms;
How to use Simple Ajax Beginform in Asp.net MVC 4?
Or you could make your own ajax implementation
https://www.c-sharpcorner.com/blogs/using-ajax-in-asp-net-mvc
Or you could just go ahead and bind everything on your model;
// don't need to specify which properties to bind, all of the available properties in your view will be bound to the model on POST
public ActionResult Edit(EMP eMP)
{
if(eMP.FirstName!=null ...){
// ... do some checking depending on what values are submitted
}
// save profile here
// when you return the view
return View(eMP);
}
but for this method you need to only have 1 form for Personal,Job, and Others.
#{ Html.RenderAction("Index", "EMP_REFERENCE", new { id = Model.eMP.lineno });}
#{ Html.RenderAction("Index", "EMP_BENEFITS", new { id = Model.eMP.lineno });}
#using (Html.BeginForm("Edit", "EMPs", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<!--put all your employee input fields here-->
<div class="form-group">
<div class="pull-right">
<input type="submit" value="Update" name="submit" class="btn btn-success" />
</div>
</div>
<!--put all your job input fields here-->
<div class="form-group">
<div class="pull-right">
<input type="submit" value="Update" name="submit" class="btn btn-success" />
</div>
</div>
<!--put all your others input fields here-->
<div class="form-group">
<div class="pull-right">
<input type="submit" value="Update" name="submit" class="btn btn-success" />
</div>
</div>
}

Bad Request MVC HttpPost

I have the following cshtml file.
#model Models.AuthorizeUser
#{
ViewBag.Title = "Authorize";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
<div class="card card-container">
<img class="profile-img-card" src="~/Content/images/rblogo_reverse-pms348_000.gif" />
<p> </p>
<form method="POST">
<p>Hello, #Model.Name</p>
<p>A third party application want to do the following on your behalf:</p>
<ul>
#foreach (var scope in Model.Scopes)
{
<li>#scope.ScopeDescription</li>
}
</ul>
<div class ="row">
<div class="col-md-4">
<button class="btn btn-block btn-primary btn-signin" name="submit" type="submit" value="authorize">Grant</button>
</div>
<div class="col-md-8">
<button class="btn btn-block btn-primary btn-signin btn-small-text" name="submit" type="submit" value="logout">Sign in as different user</button>
</div>
</div>
</form>
</div>
</div>
I have my controller file as follows:
public class OAuthController : Controller
{
[HttpGet]
public ActionResult Authorize()
{
logger.Trace("Authorize method entered");
AuthorizeUser authorizeUser;
......
return View(authorizeUser);
}
[HttpPost]
public ActionResult Authorize(AuthorizeUser authorizeUser, string submit)
{
logger.Trace("Authorize with object");
if (Response.StatusCode != 200)
{
logger.Trace("status code " + Response.StatusCode);
logger.Trace("status description " + Response.StatusDescription);
return View("AuthorizeError");
}
..............
}
When the form is displayed, the info is displayed correctly. After I click Grant button, I got Response.StatusCode == 400. Both authorizeUser and submit are null. I am expecting StatuCode == 200 with values of authrizeUser and submit.
Have you tried using Html.BeginForm()?
Instead of using <form method="POST"> you could use Html.BeginForm("Action", "Controller")

Ajax.BeginForm works first time, but calls method twice from second call

Ajax.BeginForm works first time, but calls method twice from second call.. I have referenced all the required scripts.
Firstly, In my main view, I have a common div for two partail views and I am loading respective views based on a radio button selection.
My Select Partial View
<div>
#using (Ajax.BeginForm("GetRandomThirdPartyList", "RandomList", new AjaxOptions { UpdateTargetId = "Contractors" }, new { id = "FORM" }))
{
<div id="Contractors">
<div id="ThirdParty">
<br />
<h3>Third Party Contractors</h3><hr />
<div>Enter High Risk Percentage: #(Html.Kendo().TextBoxFor<int?>(model => model.HighThirdPercent)
.HtmlAttributes(new { style = "width: 50px; height:25px" })
)
</div>
<input type="submit" value="Generate Report" class="k-button btn-primary" id="btn_thirdpaty" />
#* <b>#Html.DisplayFor(model => model.TotHighRisk) HighRisk Employees / #(Html.DisplayFor(model => model.TotLowRisk)) LowRisk Employees</b>*#
</div>
<br />
<div id="ThirdPartytab">
<div id="ReportForm" class="k-content">
<ul id="tabstrip2" class="nav nav-tabs" role="tablist">
<li class="active">HighRisk Third Party Contractors</li>
#* <li style="float:right"><img src="~/Images/icon_ssrs.png" title="Export to SSRS" /></li>*#
</ul>
#*Tab Content Containers*#
<div class="tab-content">
#if (Model.ThirdParty != null)
{
<div class="tab-pane fade in active" id="ThirdPartytab"> #Html.Partial("ThirdParty", Model) </div>
}
</div>
</div>
</div>
</div>
}
My Controller :
int tphigh = 0;
// GET: /RandomList/
[HttpPost]
public ActionResult GetRandomThirdPartyList(VM.RandomList random)
{
// tphigh=Convert.ToInt32(random.HighThirdPercent);
if (random.HighThirdPercent != null)
{
tphigh = Convert.ToInt32(random.HighThirdPercent);
// RedirectToAction("HighRiskCOPL", high);
}
List<VM.RiskList> risklist = (List<VM.RiskList>)AutoMapDomainModel<List<VM.RiskList>>(randomDBentity.GetRandomList(0, 0, tphigh,null));
mainlist.HighThirdPercent = tphigh;
mainlist.ThirdParty = //some list as third party is a Ienumerable
return PartialView("ThirdPartyContractors",mainlist);
}
The form posts properly first time, but from second time, it calls all the code lines in the action method tiwce, sometimes in a haphazard order and finally either populates the grid, or doesnt send any result.
Solved it.. My updatetargetid div was not the parent div..
replaced that..

Partial view doesn't load inside current view

So I have this partial view:
#model QueryQuestionManager.Models.Domain.Answer
<script src="~/Scripts/DynamicList.js"></script>
<div class="editorRow">
#using (Html.BeginCollectionItem("Answers"))
{
<div>
#Html.LabelFor(x => x.AnswerText)
#Html.EditorFor(x => x.AnswerText)
</div>
delete
}
</div>
I want to load this partial view in my main view when someone clicks the link:
#model QueryQuestionManager.Models.Domain.Question
#{
ViewBag.Title = "Create";
}
<script src="~/Scripts/DynamicList.js"></script>
<br />
#using (Html.BeginForm(new { #class = "form", role = "form" }))
{
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(m => m.QuestionText)
</div>
<div class="form-control">
#Html.TextBoxFor(m => m.QuestionText)
#Html.ValidationMessageFor(m => m.QuestionText)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Category)
</div>
<div class="form-control">
#Html.TextBoxFor(m => m.Category)
#Html.ValidationMessageFor(m => m.Category)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Answers)
</div>
<br />
<div id="editorRows">
#foreach (var item in Model.Answers)
{
#Html.Partial("EditorRow", item);
}
</div>
#Html.ActionLink("Add another...", "BlankEditorRow", "Question", new { id = "addItem" })
<br />
<input type="submit" value="Save" class="btn btn-success" />
</div>
}
<br />
<div>
#Html.ActionLink("Back to List", "Index", "Home")
</div>
This is the action result from the controller
public ActionResult BlankEditorRow()
{
return PartialView("EditorRow", new Answer());
}
And then I have a javascript file for the dynamic adding and deleting partial views.
$('#addItem').click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) {
$('#editorRows').append(html);
}
});
return false;
});
$('a.deleteRow').live('click', function () {
$(this).parents('div.editorRow:first').remove();
return false;
});
But for some reason my partial view doesn't load inside my current view and it opens only the partial view.
Am I forgetting something?
I'm thinking you don't want that action link. I believe your jQuery click handler has the correct approach, but your action link is linking to your new URL (Question/BlankEditorRow) and you don't want that. Rather you just need to fetch this html, and insert it as you do, but WITHOUT navigating the main page to that URL.
Instead of the ActionLink, use an anchor tag and a hidden field.
<a id="addItem" href="#" />
<input type="hidden" id="partialViewAction" value="#Url.Action("BlankEditorRow","ControllerName")"
Now in your ajax call, instead of using the href property of the anchor, use the value of the hidden field.
url: $('#partialViewAction').val()

Resources