How to toggle Partial View on Single Submit Button in MVC? - asp.net-mvc

Here is my Code
View
#using (Html.BeginForm("userrights", "Users", FormMethod.Post, new { #class = "form-horizontal", role = "form"}))
{
<div class="form-group">
<div class="col-md-7" style="padding-right:10px">
#Html.TextBoxFor(m => m.companyname, new { #class = "form-control", #placeholder = "Serach By Sponser Name" })
</div>
<div class="clearfix"></div>
</div>
<div class="form-group">
<div class="col-sm-2">
<button type="submit" id="btn_search" value="Search" name="btn_search" class="btn btn-default">Search</button>
</div>
<div class="clearfix"></div>
</div>
</div>
#Html.Partial("_userRightPartial", Model._UserRightPartialView)
<div class="clear"></div>
}
Controller Method
public ActionResult userrights()
{
IEnumerable<MenuListModel> _MenuListModel = _ftwCommonMethods.GetMenuItems();
IEnumerable<SubMenuListModel> _SubMenuListModel = _ftwCommonMethods.GetSubMenuItems("1");
UserRightViewSearch _UserRightViewSearch = new UserRightViewSearch();
UserRightPartialView _UserRightPartialView = new UserRightPartialView();
_UserRightPartialView._SubMenuListModel = _SubMenuListModel;
_UserRightViewSearch._UserRightPartialView = _UserRightPartialView;
_UserRightViewSearch._menu = _MenuListModel;
_UserRightViewSearch.selectedMenu = 0;
return View(_UserRightViewSearch);
}
I want when page first time loads, _userRightPartial partial view should be hidden. After Submitting By Search Button it should appear.
I know it can be possible by Hide and Show DIV. But i want is there other way to do it with MVC Code?

Related

How to redirect button that is inside Html.BeginForm

I have this View which displays 3 text boxes and a drop down list for displaying nationalities. The form itself works just fine, posts back to the controller and nothing is wrong. However what i want is, say a nationality is not present in the drop down and a user clicks a button which would redirect to a different page where they can add a nationality. Here is what i have so far:
#model WebApp.Models.ViewModels.AddPersonViewModel
<div class="container card">
#using (Html.BeginForm("AddPersonPost", "Persons", FormMethod.Post))
{
<form>
<div class="form-row">
<div class="col">
#Html.TextBoxFor(m => m.PersonModel.Name, new { #class = "form-control", #placeholder = "Name" })
</div>
<div class="col">
#Html.TextBoxFor(m => m.PersonModel.Relationship, new { #class = "form-control", #placeholder = "Relationship" })
</div>
<div class="col">
#Html.TextBoxFor(m => m.PersonModel.Comment, new { #class = "form-control", #placeholder = "Comment" })
</div>
<div class="col dropdown show">
#Html.DropDownListFor(m => m.PersonModel.Nationality, Model.NationalityList)
<input type="submit" class="btn-sm btn-primary mt-1" value="Add Nationality" onclick="window.location='#Url.Action("GetAll", "Persons")'">
</div>
</div>
<div class="m-sm-2">
<input type="submit" class="btn-sm btn-primary" value="Add Person">
</div>
</form>
}
</div>
I have tried the redirect option but when i click the button to add nationality it keeps going to the Action in the BeginForm, not to the intended Action in the button. So i was wondering 1. is this good practice to do what i am attempting to do? 2. How to go about it? Any help is appreciated.

bootstrap modal to appear when dropdownlist item is selected in mvc

I want a bootstrap modal with partial view to popup when a user selects the dropdownlist item.
For each selected item the popup should refresh with new content when the user selects a different item in the dropdownlist. From the code below, I could able to make the ajax and then redirect to partial view with model values but unable to display the modal popup
Index.cshtml
<div class="form-group">
#Html.LabelFor(model => model.SelectedIssue, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.DropDownListFor(model => model.SelectedIssue, Model.IssueDetails, "Please Select", new { #class = "form-control", #id = "IssueId" })
#Html.ValidationMessageFor(model => model.SelectedIssue, "", new { #class = "text-danger" })
</div>
</div>
$("#IssueId").change(function () {
$.ajax({
type: 'GET',
url: '#Url.Action("GetActionDetails")',
dataType: 'html',
data: { id: $("#IssueId").val() },
success: function (data) {
$('#modal-content').html(data);
$('#modal-container').modal('show');
},
error: function (ex) {
alert('Failed to retrieve action details' + ex);
}
});
return false;
});
The dropdown selection is making an ajax call and calling the below method in the controller
public ActionResult GetActionDetails(string id)
{
ActionDetails model = new ActionDetails();
model.ActionTaken = "Action Taken ";
model.AdviceGiven = "Advice Given to";
return PartialView("ActionDetails", model);
}
This is then redirecting to PartialView ActionDetails view which is below.
#model OnCallLogging.Models.ActionDetails
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 class="modal-title">Action Details</h3>
</div>
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(m => Model.ActionTaken, new { #class = "control-label col-sm-3"})
<div class="col-sm-9">
#Html.DisplayFor(m => m.ActionTaken, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => Model.AdviceGiven, new { #class = "control-label col-sm-3" })
<div class="col-sm-9">
#Html.DisplayFor(m => m.AdviceGiven, new { #class = "form-control" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-warning" data-dismiss="modal">Close</button>
</div>
And in the Layout.cshtml, the following markup is written before the body closing tag.
<div id="modal-container" class="modal fade hidden-print" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
and in the script.css
.modal-content {
width: 600px !important;
margin: 30px auto !important;
}
When I run the code, the screen goes dim but no popup appears. When I debug I could see ajax calling the controller action and redirecting to partial view, but the popup does not appear.
Not sure what am I missing to show the popup with model properties. Could anyone please help.
Since you are seeing the controller action being called while debugging, the harder part is working. The most likely explanation for your issue is in your javascript "success:":
//change from this:
$('#modal-content').html(data);
//to this:
$('.modal-content').html(data);
You can optionally, change your <div class="modal-content"> to <div id="modal-content">

two submit buttons for different form within the same view and controller

I have a view screen that has two different form on it, that will be activated differently. if the first button is clicked, the first form comes up and the user can fill and submit after which he proceed to click the other button to activate the other form which will then be submitted to a different table. I tried giving it different each submit button different name but my controller isn't recognizing the name. any help will be appreciated.
this is my view presently
<div class="container">
<form class="form-horizontal" role="form" method="post" id="head">
<div class="form-group">
<label for="warehouse" class="col-sm-2 control-label">Transaction type</label>
<div class="col-sm-7">
#Html.TextBoxFor(m => m.vwint0, ViewBag.action_flag == "Create" ? (object)new { #class = "form-control", style = "width : 120px", #maxlength = 10 } : new { #disabled = "disabled", style = "width : 120px" })
#Html.ValidationMessageFor(m => m.vwint0)
</div>
</div>
<div class="form-group">
<label for="code" class="col-sm-2 control-label">Customer code</label>
<div class="col-sm-7">
#Html.DropDownListFor(m => m.vwstring1, ViewBag.cus as SelectList, "Select", new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
<button type="submit" class="btn btn-primary" name="update" value="headsub">Submit</button>
</div>
</div>
</form>
<form class="form-horizontal" role="form" method="post" id="details">
<div class="form-group">
<label for="firstName" class="col-sm-2 control-label">Sale sequence number </label>
<div class="col-sm-9">
#Html.TextBoxFor(m => m.vwint0, new { #class = "form-control", style = "width : 80px", maxlength = 10 })
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Quote sequence</label>
<div class="col-sm-9">
#Html.TextBoxFor(m => m.vwstring9, new { #class = "form-control", style = "width : 80px", maxlength = 10 })
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Item code</label>
<div class="col-sm-9">
#Html.DropDownListFor(m => m.vwstring10, ViewBag.item as SelectList, "Select", new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
<button type="submit" class="btn btn-primary" name="update" value="detailsub">Submit</button>
</div>
</div>
</form>
</div>
In my controller, I tried this but my controller isn't even recognizing the button name.
if (update == "headsub")
{
AR_002_SALES gdoc = new AR_002_SALES();
gdoc.sale_sequence_number = glay.vwint0;
gdoc.customer_code = glay.vwstring1;
gdoc.currency_code = glay.vwstring2;
}
else
{
AR_002_QUOTE = new AR_002_QUOTE();
AR_002_QUOTE.sale_sequence_number = glay.vwint0;
AR_002_QUOTE.quote_sequence = glay.vwstring9;
AR_002_QUOTE.item_code = string.IsNullOrWhiteSpace(glay.vwstring10) ? "" : glay.vwstring10;
AR_002_QUOTE.quote_qty = glay.vwdclarray0[0];
AR_002_QUOTE.price = glay.vwdclarray0[1];
}
Instead of using <form class="form-horizontal" role="form" method="post" id="head">
use #using (Html.BeginForm("ActionMethod", "Controller", FormMethod.Post, new { #class = "form-horizontal" ,#id="head" }))
to submit a form and action method will process that form and does stuff.Similarly you can do for another form also.
In your .cshtml it looks like it will not hit any action method of that controller.

Retrieving dropdown values from partial view during post method

I need to get the selected dropdown value from partial view and included in the CategoryID in the Book class...
[Authorize]
public PartialViewResult GetAllCategory()
{
ProcessSVC.Category newCategory = new ProcessSVC.Category();
newCategory.ChildCategories = obj1.GetAllCategories(String.Empty);
return PartialView(newCategory);
}
GetAllCategory.cshtml (PartialView)
#model MvcAdminTemplate.ProcessSVC.Category
#Html.DropDownListFor(m => m.ParentID, new SelectList(Model.ChildCategories, "ID", "DisplayName"), new { #class = "form-control" })
Create View:
[Authorize]
[HttpPost]
public ActionResult Create()
{
MvcAdminTemplate.ProcessSVC.Book oBook = new ProcessSVC.Book();
return View(oBook);
}
Create.cshtml
#model MvcAdminTemplate.ProcessSVC.Book
#{
ViewBag.Title = "Create";
}
#Html.Partial("_LeftMenu")
<!-- content -->
<h2>Create</h2>
<div class="col-md-10">
#using (Html.BeginForm("Create", "Books", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="row">
<div class="bootstrap-admin-no-table-panel-content bootstrap-admin-panel-content collapse in">
<form class="form-horizontal">
<fieldset>
<legend>Add Book</legend>
<div class="form-group">
<div class="col-lg-2">
#Html.LabelFor(m => m.BookName, new { #class = "control-label" })
</div>
<div class="col-lg-10">
#Html.TextBoxFor(m => m.BookName, new { #class = "form-control", type = "text" })
<p class="help-block"> </p>
</div>
</div>
<div class="form-group">
<div class="col-lg-2">
#Html.LabelFor(m => m.Description, new { #class = " control-label" })
</div>
<div class="col-lg-10">
#Html.TextBoxFor(m => m.Description, new { #class = "form-control ", type = "text" })
<p class="help-block"> </p>
</div>
</div>
<div class="form-group divCategory">
<div class="col-lg-2">
#Html.Label("Parent Category", new { #class = " control-label" })
</div>
<div class="col-lg-10">
#Html.HiddenFor(m => m.BookId, new { #class = "hdn-id" })
#Html.Action("GetAllCategory","Books")
<span class="help-block"> </span>
</div>
<button type="submit" class="btn btn-primary">Save changes</button>
<button type="reset" class="btn btn-default">Cancel</button>
</div>
</fieldset>
</form>
</div>
</div>
}
After submission of the above form i need to get Book attributes and Category "Selected Category".
[Authorize]
[HttpPost]
public ActionResult Create(ProcessSVC.Book oBook)
{
oBook.LanguageID = 1;
_service.AddBooks(oBook.ActualPrice,oBook.ActualPriceString, oBook.Author, oBook.BookId, oBook.BookName, oBook.CategoryID, oBook.Currency, oBook.CurrentPrice, oBook.CurrentPriceString,
oBook.Description, oBook.DiscountPercentage, oBook.DiscountValue, oBook.LanguageID,
oBook.NativeLanguageName, oBook.Publisher);
TempData.Add("SuccessMessage", " New book " + oBook.BookName + " Added !");
return RedirectToAction("Index");
}
Please suggest me.
To correctly bind your model, you need to create the dropdown in the main view. This line in you partial view
#Html.DropDownListFor(m => m.ParentID, ....
will render a select
<select name="ParentID" ...
but you model is expecting a property named CategoryID
In you Create() method, generate the SelectList and assign to a view model property or to ViewBag and then (instead or #Html.Action("GetAllCategory","Books") use
#Html.DropDownListFor(m => m.CategoryID, ....
use this line in your GetAllCategory.cshtml file
#Html.DropDownList("CategoryID", new SelectList(Model.ChildCategories, "ID", "DisplayName"), new { #class = "form-control" })

ASP.Net MVC 5 Form in a Twitter Bootstrap Modal - Return to modal if user does not enter correct field information

I have a contact form in a Twitter Bootstrap Modal and if the user happens to not enter a name or email address and hits submit I want to return to the Modal instead of just closing the Modal. Also if the form is valid I would like to let the user know that an we will be contacting them shortly in the same modal. Is this possible?
Here is my controler.
[HttpPost]
public ActionResult Index(Contact model)
{
ViewBag.IsValid = false;
ViewBag.CaptchaError = "";
RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();
if (String.IsNullOrEmpty(recaptchaHelper.Response))
{
ViewBag.CaptchaError = "The Captcha cannot be empty";
return View();
}
RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
if (recaptchaResult != RecaptchaVerificationResult.Success)
{
ViewBag.CaptchaError = "The Captcha was incorrect";
return View();
}
if (ModelState.IsValid)
{
SendSupportEmail(model);
ViewBag.isValid = true;
}
return View();
}
Here is my view with the Modal
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content col-md-12">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Contact Us</h4>
</div>
<center>
<div class="modal-body">
#using (Html.BeginForm())
{
if ((bool)ViewBag.IsValid)
{
}
else
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-12">
#Html.TextBoxFor(model => model.Name, new { #class = "form-control", placeholder = "Name" })
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.TextBoxFor(model => model.Phone, new { #class = "form-control", placeholder = "Phone" })
#Html.ValidationMessageFor(model => model.Phone)
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.TextBoxFor(model => model.Email, new { #class = "form-control", placeholder = "E-Mail Address" })
#Html.ValidationMessageFor(model => model.Email)
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.TextAreaFor(model => model.Comments, new { #class = "form-control", height = "40", placeholder = "Comments" })
#Html.ValidationMessageFor(model => model.Comments)
</div>
</div>
<div class="form-group">
#if (!string.IsNullOrEmpty(ViewBag.CaptchaError))
{
<span class="field-validation-error">#ViewBag.CaptchaError</span>
}
#Html.Recaptcha(theme: Recaptcha.Web.RecaptchaTheme.Clean)
</div>
<div class="form-group">
<div class="col-md-12">
<input type="submit" id="submit" value="Submit" class="btn btn-default btn-lg btn-primary col-sm-12" />
</div>
</div>
</div>
}
}
</div>
</center>
</div>
</div>
I have searched everywhere and was unable to find a solution.
Don't have enough rep to comment - hence the answer. I reckon the easiest way to do this would be to use ajax. User jquery validation plugin to validate user input on submit click. This way, the validation messages can be displayed on the modal itself and the page doesn't have to be refreshed.
On successful validation, the form can be posted to your controller action. You can send a success message as part of your response and display it as a popup or a notification using notifyjs or your own code.

Resources