I need to call a controller by passing the param from the view on clicking the ActionLink - asp.net-mvc

I am trying to search a student and display the student record based on the value entered on textbox. I am not sure how to pass the value without using Jquery. Is there a way.
Controller:
[Authorize]
public ActionResult GetStudentsByName(string name)
{
SchoolDbEntities db = new SchoolDbEntities();
var student = db.Students.Where(s => s.StudentName.Contains(name));
return View(student);
}
View
<div class="panel-body">
<div class="form-group">
#Html.LabelFor(m=> m.SearchEntity.StudentName,"Search Student")
#Html.TextBoxFor(m => m.SearchEntity.StudentName, new { #class = "form-control" })
</div>
</div>
<div class="panel-footer">
<button type="button" onclick="location.href='#Url.Action("GetStudentsByName", "Student")'" class="btn btn-primary">Search <i class="glyphicon glyphicon-search"></i></button>
<button id="Reset"
class="btn btn-primary btn-sm">
<i class="glyphicon glyphicon-share-alt"></i> Reset
</button>
</div>
I need to pass the param , In the #Url.Action("GetStudentsByName", "Student", new {#name= 'value from the textbox')
Also it is a Get Method and not httpPost.

You can keep the input form element inside a form control and submit the form via GET method.
Make sure the input element name matches with your action method parameter name
#using (Html.BeginForm("GetStudentsByName","Student",FormMethod.Get))
{
<input type="text" name="name"/>
<button type="submit" class="btn btn-primary">Search </button>
}

If you dont wanna make the button a submit button then by giving your text box a specific class you can do it .
<div class="panel-body">
<div class="form-group">
#Html.LabelFor(m=> m.SearchEntity.StudentName,"Search Student")
#Html.TextBoxFor(m => m.SearchEntity.StudentName, new { #class = "form-control,txt-input" })
</div>
</div>
<div class="panel-footer">
<button type="button" onclick="location.href='#Url.Action("GetStudentsByName", "Student",new { data= "STUDENT_NAME" })'.replace("STUDENT_NAME", $('.txt-input').val())" class="btn btn-primary">Search <i class="glyphicon glyphicon-search"></i></button>
<button id="Reset"
class="btn btn-primary btn-sm">
<i class="glyphicon glyphicon-share-alt"></i> Reset
</button>
</div>
I tried something like this long back , i think it should work.

Try this
View
#using (Html.BeginForm("GetStudentsByName", "Home"))
{
<div class="form-group">
#Html.LabelFor(m => m.StudentName, "Search Student")
#Html.TextBoxFor(m => m.StudentName, new { #class = "form-control" })
</div>
<input type="submit" value="Search" class="btn btn-primary" />
}
</div>
Controller
public ActionResult GetStudentsByName()
{
string name = Request.Form["StudentName"]
SchoolDbEntities db = new SchoolDbEntities();
var student = db.Students.Where(s => s.StudentName.Contains(name));
return View(student);
}
using Request.Form["StudentName"] you can access the value from view to controller. Also, one more suggestion, use using statement it helps to manage unhandled memory. For example
public ActionResult GetStudentsByName()
{
string name = Request.Form["StudentName"]
using(SchoolDbEntities db = new SchoolDbEntities())
{
var student = db.Students.Where(s => s.StudentName.Contains(name));
return View(student);
}
}

Related

Error passing between Model and ViewModel?

In the previous question "ASP .NET Core Repository Id Article passed in was changed to 0?" I did it successfully, but due to a conflict with the team on GitHub, I had to rewrite my code. However, when I run it, I have a transmission error between Model and ViewModel. What is this and how do I fix it? I don't change anything between my code.
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditArticle(Article article)
{
if(!ModelState.IsValid)
{
return View(article);
}
if(!_studentRepository.EditArticle(article))
{
throw new ArgumentException("...");
}
return RedirectToAction("Index");
}
View
#model Megatron.ViewModels.ArticleFacultyViewModel
#{
ViewData["Title"] = "Edit Article";
}
<div>
<form asp-action="EditArticle">
<partial name="_StatusMessage" model="#ViewData["Message"]" />
<div>
#Html.HiddenFor(a => a.Article.Id)
<div class="form-group row">
<div class="col-2">
<label asp-for="Article.Title" class="col-form-label"></label>
</div>
<div class="col-5">
<input asp-for="Article.Title" class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="col-2">
<label class="col-form-label">Type of contribution</label>
</div>
<div class="col-3">
<button hidden class="btn btn-primary" type="button" data-toggle="collapse" data-target="#ImportFileCollapse" aria-expanded="false" aria-controls="ImportFileCollapse">
</button>
<button hidden class="btn btn-primary" type="button" data-toggle="collapse" data-target="#TextAreaCollapse" aria-expanded="false" aria-controls="TextAreaCollapse">
</button>
<button id="button-collapse" class="btn btn-primary" type="button" data-toggle="collapse" data-target=".multi-collapse" aria-expanded="false" aria-controls="ImportFileCollapse TextAreaCollapse">
Switch to Editor
</button>
</div>
</div>
You return a Artical type model to the View in the post method,
if(!ModelState.IsValid)
{
return View(article);
}
While the view expect a
ArticleFacultyViewModel type model. You may convert it.
if(!ModelState.IsValid)
{
var articleVM = new ArticleFacultyViewModel
{
Article = article,
Faculties = _facultyRepository.GetFaculties()
};
return View(articleVM);
}

mvc radiobuttonfor in editortemplate keyboard navigation does not set model

Context:
Model generating some RadioButtonFor groupings as input to answer questions.
What is happening:
Case 1. When mouse click on a radio option the display looks correct. When the [HttpPost] ActionResult(model) for the page is triggered the Model.Answer comes through with the correct value. Which is good and desired.
Case 2. When navigating with the keyboard to the radio group and selecting one with arrow keys the display looks correct. But when the [HttpPost] ActionResult (model) is triggered the Model.Answer value is unchanged from what it was loaded as on page load.
Here is the code that makes the radio group:
#model NexusPWI.ViewModels.Wizard.QuestionModel
#* Dynamically generate and model bind controls for QuestionModel *#
#{
<div class="row d-contents">
<div class="form-group">
<div class="question">
<div class="col-lg-2 d-contents">
<div class="btn-group btn-toggle group-sm d-contents" data-toggle="buttons">
<label class="btn QuestionRadio btn-default #(Model.Answer == YesNoNAOptions.Yes ? "active" : "")" for="#Model.Answer">
#YesNoNAOptions.Yes.ToString().ToUpper()
#Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.Yes, new { #onfocus = "radiofocus(event)", #onblur = "radioblur(event)" })
</label>
<label class="btn QuestionRadio btn-default #(Model.Answer == YesNoNAOptions.No ? "active" : "")" for="#Model.Answer">
#YesNoNAOptions.No.ToString().ToUpper()
#Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.No, new { #onfocus = "radiofocus(event)", #onblur = "radioblur(event)" })
</label>
#if (!Model.NaInvalid)
{
<label class="btn QuestionRadio btn-default #(Model.Answer == YesNoNAOptions.NA ? "active" : "")" for="#Model.Answer">
N/A
#Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.NA, new { #onfocus = "radiofocus(event)", #onblur = "radioblur(event)" })
</label>
}
</div>
</div>
<div class="col-lg-9 d-contents">
<div class="row">
<p>
<strong>#Model.Question</strong>
</p>
</div>
#Html.HiddenFor(x => Model.Question_IdentityMarker, new { #class = "Question_IdentityMarker" })
</div>
</div>
</div>
</div>
}
Here is an example of the html that is generated:
<div class="form-group">
<div class="question">
<div class="col-lg-2 d-contents">
<div class="btn-group btn-toggle group-sm d-contents" data-toggle="buttons">
<label class="btn QuestionRadio btn-default " for="No">
YES
<input data-val="true" data-val-required="The Answer field is required." id="Questions_0__Answer" name="Questions[0].Answer" onblur="radioblur(event)" onfocus="radiofocus(event)" value="Yes" type="radio">
</label>
<label class="btn QuestionRadio btn-default active" for="No">
NO
<input checked="checked" id="Questions_0__Answer" name="Questions[0].Answer" onblur="radioblur(event)" onfocus="radiofocus(event)" value="No" type="radio">
</label>
<label class="btn QuestionRadio btn-default " for="No">
N/A
<input id="Questions_0__Answer" name="Questions[0].Answer" onblur="radioblur(event)" onfocus="radiofocus(event)" value="NA" type="radio">
</label>
</div>
</div>
<div class="col-lg-9 d-contents">
<div class="row">
<p>
<strong>Do you charge sales tax?</strong>
</p>
</div>
<input class="Question_IdentityMarker" id="Questions_0__Question_IdentityMarker" name="Questions[0].Question_IdentityMarker" value="CUSTOMERSALESTAX" type="hidden">
</div>
</div>
</div>
EDIT Adding onFocus & onBlur at request:
onFocus & onBlur are css highlighting for the keyboard navigation to make it more clear for the user where they are in the page.
function radiofocus(event) {
// Get event object if using Internet Explorer
var e = event || window.event;
// Check the object for W3C DOM event object, if not use IE event object to update the class of the parent element
if (e.target) {
var addClass = focusClass(e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className, "r");
e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className = addClass;
} else {
var addClass = focusClass(e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className, "r");
e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className = addClass;
}
};
function radioblur(event) {
// Get event object if using Internet Explorer
var e = event || window.event;
var removeClass = focusClass("", "r").trim();
// Check the object for W3C DOM event object, if not use IE event object to update the class of the parent element
if (e.target) {
e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className = e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className.replace(removeClass, "");
} else {
e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className = e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className.replace(removeClass, "");
}
};
Why do the keyboard navigated changes not get back to the controller?
Anything to add to make this clearer?
Side note: For some reason before a value is chosen in the radio group the keyboard tab navigation is stopping for each radio answer for a question.

MVC refresh table data in modal using entity framework

good day. how can I refresh a modal table data? well, I have this textbox that when a user clicks show a modal pop-up. inside the pop-up is a partial view with the table and a search. When a user searches, instead of reloading the value in the modal, it redirects me to the partial view itself. I have seen a lot of examples like this one -- https://forums.asp.net/t/2098629.aspx?Advance+search+in+a+MVC+Popup+Window+ -- but still cannot go through it. its basically a modal popup but contains a partial view in it, once the search was clicked, just need to reload the table and no more. thanks in advance
Partial View Code:
public ActionResult ShowTaxPayer(int? page, string searchString)
{
var user = (from u in db2.Payers
select new Taxpayer
{
ID = u.objid,
Firstname = u.firstname,
Lastname = u.lastname,
Middlename = u.middlename,
Address = u.primaryaddress
});
if (string.IsNullOrEmpty(searchString))
{
return View(user.ToList().ToPagedList(page ?? 1, 10));
}
else
{
return View(user.Where(s => s.Firstname.Contains(searchString)).ToList().ToPagedList(page ?? 1, 10));
}
}
Razor:
#using (Html.BeginForm("Index", "Wizard", FormMethod.Post))
{
#Html.ValidationSummary(true)
<fieldset>
<div class="wizard-step">
#Html.Label("Taxpayer Name")
#Html.TextBoxFor(m => m.taxpayername, new { data_toggle = "modal", data_target = "#myModal", data_backdrop = "static", data_keyboard = "false" })
#Html.ValidationMessageFor(m => m.taxpayername)
</div>
<div class="wizard-step">
#Html.Label("Taxpayer Address")
#Html.EditorFor(m => m.taxpayeraddress)
#Html.ValidationMessageFor(m => m.taxpayeraddress)
</div>
<div class="wizard-step">
#Html.Label("Trade Name")
#Html.EditorFor(m => m.tradename)
#Html.ValidationMessageFor(m => m.tradename)
</div>
<div class="wizard-step confirm">
</div>
<p>
<input type="button" id="back-step" name="back-step" value="<-- Back" />
<input type="button" id="next-step" name="next-step" value="Next -->" />
</p>
</fieldset>
}
The Modal:
<div class="modal fade" id="myModal" 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>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
#{Html.RenderAction("ShowTaxPayer", "Wizard");}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
I just need to load the data from my model in the modal and not redirect me to the actual view. Thanks in advance.
Here the Model Popup
<div class="modal-body">
#{Html.RenderAction("ShowTaxPayer", "Wizard");}
</div>
and changed to
<div class="modal-body" id="popupTableName">
</div>
and Add Javascript
<script>
window.onload = LoadTable();
function LoadTable(){
$.get( '#Url.Action("actionName","ControllerName", new { id = Model.ID } )', function(data) {
$('#popupTableName').html(data);
});
}
function onChange(){
LoadTable();
}
</script>

getting null value for HttpPostedFileBase in mvc controller

I want to give user the option to change their profile picture.On hitting the save button my controller action is hit but I get null value for HttpPostedFileBase.I am uploading files first time in mvc so not able to figure out where I am doing wrong and hence getting null value in controller.
controller
[AuthenticationRequired]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ChangeProfilePicture(HttpPostedFileBase imageData)
{
}
view
#using (Ajax.BeginForm("ChangeProfilePicture", "Account", new { enctype = "multipart/form-data" },new AjaxOptions { OnSuccess = "OnSuccess" }))
{
#Html.AntiForgeryToken()
<div class="modal-body" id="tilesDescription">
<div class="row">
<div class="col-md-12">
<div class="text-center">
<div class="fileUpload btn btn-primary">
<span>Select a photo from your computer</span>
<input id="uploadBtn" type="file" class="upload" name="imageData" accept="image/*" />
</div>
<div class="text-center">
<img id="imgprvw" alt="uploaded image preview" class="imgPreview hide" />
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-rounded btn-sm btn-tiles" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-rounded btn-sm btn-tiles disabled" id="btnProfilePic">Set as profile picture</button>
</div>
}
You cannot post your file using ajax like that, cause is not supported.
From my experience, the easiest way to get files posted using Ajax (if using jquery), is using :
http://malsup.com/jquery/form/

ASP.Net MVC Show/Hide Content

Ok I have the following View
#model IEnumerable<WebApplication3.Models.user>
#{
ViewBag.Title = "Password Management";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section title {<h1>#ViewBag.Title</h1>}
<div id="page-block" class="page-block-three row">
<div style="margin-top: 30px;" class="col-lg-offset-2 col-lg-8">
#using (Html.BeginForm())
{
<div class="input-group">
#Html.TextBox("SearchString", null, new { #class = "form-control ccl-form", #style = "z-index: 10", #placeholder = "Enter Username"})
<div class="input-group-btn">
<button class="btn ccl-btn ccl-btn-red ccl-btn-search" type="submit"><i class="fa fa-search"></i></button>
</div>
</div>
}
</div>
<div class="col-lg-offset-3 col-lg-6">
#foreach (var item in Model)
{
<div class="details-block">
#Html.DisplayFor(modelItem => item.UserName)
<button type="button" class="btn ccl-btn ccl-btn-green ccl-btn-search pull-right">Select User</button>
</div>
}
</div>
</div>
What I want to be able to do is hide the following div
<div class="col-lg-offset-3 col-lg-6">
#foreach (var item in Model)
{
<div class="details-block">
#Html.DisplayFor(modelItem => item.UserName)
<button type="button" class="btn ccl-btn ccl-btn-green ccl-btn-search pull-right">Select User</button>
</div>
}
</div>
Then show that Div when the submit button is clicked
My Controller looks like the following
public class PasswordController : Controller
{
private CCLPasswordManagementDBEntities db = new CCLPasswordManagementDBEntities();
public ActionResult Search(string searchString)
{
var users = from x in db.users select x;
if (!String.IsNullOrEmpty(searchString))
{
users = users.Where(x => x.UserName.ToUpper().Contains(searchString.ToUpper()));
}
return View(users);
}
}
At the moment the div is constantly shown and updates when the submit button is pressed but I want to hide that div until someone presses the submit button then it can show.
Thanks in advance for the help.
Change your code in the controller to this:
public ActionResult Search(string searchString)
{
var users = from x in db.users select x;
ViewBag.ShowList = false;
if (!String.IsNullOrEmpty(searchString))
{
ViewBag.ShowList = true;
users = users.Where(x => x.UserName.ToUpper().Contains(searchString.ToUpper()));
}
return View(users);
}
And change your view to this:
#model IEnumerable<WebApplication3.Models.user>
#{
ViewBag.Title = "Password Management";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section title {<h1>#ViewBag.Title</h1>}
<div id="page-block" class="page-block-three row">
<div style="margin-top: 30px;" class="col-lg-offset-2 col-lg-8">
#using (Html.BeginForm())
{
<div class="input-group">
#Html.TextBox("SearchString", null, new { #class = "form-control ccl-form", #style = "z-index: 10", #placeholder = "Enter Username"})
<div class="input-group-btn">
<button class="btn ccl-btn ccl-btn-red ccl-btn-search" type="submit"><i class="fa fa-search"></i></button>
</div>
</div>
}
</div>
#if(ViewBag.ShowList){
<div class="col-lg-offset-3 col-lg-6">
#foreach (var item in Model)
{
<div class="details-block">
#Html.DisplayFor(modelItem => item.UserName)
<button type="button" class="btn ccl-btn ccl-btn-green ccl-btn-search pull-right">Select User</button>
</div>
}
</div>
}
</div>
You can try having a flag (ViewBag.isShown = false;)
When the page refreshes, it will show your div.
Code should be like below:
if (ViewBag.isShown == true)
{
..your for each block..
}

Resources