Calling JavaScript function as parameter in #Url.Action - javascript

So I am trying to return a value from a text box as the parameter to another controller action that returns another partial. I think it would easier to just post some sample code rather than trying to explain what I am trying to do, so here is some sample code:
CSHTML:
<div class="row">
<div class="pt-sm-30 pb-xs-30 has-50px-footer">
<div class="col-lg-offset-1 col-lg-10">
<h3>CREATE A NEW PERSON PROFILE</h3>
<form class="form-spacers">
<div class="form-group">
<div class="row">
<div class="col-md-6">
<label class="input-label" for="functionalRole">First Name <span class="ReqField">*</span></label>
#Html.TextBoxFor(model => model.Person.FirstName, new { #class = "form-control input-sm", #id = "firstName", #type = "text" })
</div>
<div class="col-md-6">
<label class="input-label" for="functionalRole">Last Name <span class="ReqField">*</span></label>
#Html.TextBoxFor(model => model.Person.LastName, new { #class = "form-control input-sm", #id = "lastName", #type = "text" })
</div>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-8 col-md-9 col-lg-10 new-profile-footer">
<div class="col-lg-offset-1 col-lg-5 col-md-4 hidden-sm hidden-xs" style="margin-top: 16px;">
</div>
<div class="col-lg-6 col-md-8 col-sm-12" style="margin-top: 10px; text-align: right;">
<div class="row" style="white-space: nowrap;">
<button class="btn btn-primary button-blue btn-xs-110" onclick="location.href='#Url.Action("Index", "DirectoryMaintainer")'"><i class="fa fa-times-circle-o icon-xs-hidden" aria-hidden="true" style="padding-right: 5px;"></i>CANCEL</button>
<button id="continue" type="button" class="btn btn-success button-green btn-xs-110">CONTINUE<i class="fa fa-caret-right icon-xs-hidden" style="padding-left: 5px;" aria-hidden="true"></i></button>
</div>
</div>
</div>
</div>
<script>
$("#continue").click(function () {
$("#partialViewDiv").load('#(Url.Action("RecordsMatch", "DirectoryMaintainer", new { #firstName = getFirstName(), #lastName = getLastName()}, Request.Url.Scheme))');
});
function getFirstName() {
return document.getElementById("firstName").value;
}
function getLastName() {
return document.getElementById("lastName").value;
}
</script>
Controller:
public PartialViewResult RecordsMatch(string firstName, string lastName)
{
//Do some logic with parameters here
return PartialView("_RecordsMatch");
}
So the issue I am having this that the line
$("#partialViewDiv").load('#(Url.Action("RecordsMatch", "DirectoryMaintainer", new { #firstName = getFirstName(), #lastName = getLastName()}, Request.Url.Scheme))');
is giving me an error on getFirstName() and getLastName(). The error is "The name getFirstName() does not exist in the current context". I am pretty new to MVC so I'm not sure if this is even possible or if there is a better way of doing it. If there is, then I am more than happy to learn it. Any and all suggestions would be greatly appreciated.

You cannot mix c# and js like that as the Url.Action gets executed in the server before your js code
Basically any C# code in your razor view gets executed by the razor view engine in the server and output of that (which is HTML/plain text) will be send to the browser. All your javascript code gets executed in the browser.
You can use Url.Action to generate the base url (without route value parameters) and add query strings to that at client side later.
$(function(){
$("#continue").click(function () {
var url='#Url.Action("RecordsMatch", "DirectoryMaintainer")';
url = url+'?firstName='+ getFirstName()+'&lastName='+getLastName();
$("#partialViewDiv").load(url);
});
});
When razor executes this code, it will render output like this (you can check the page view source and see this)
$(function(){
$("#continue").click(function () {
var url='/DirectoryMaintainer/RecordsMatch';
url = url+'?firstName='+ getFirstName()+'&lastName='+getLastName();
$("#partialViewDiv").load(url);
});
});

Related

How call controller after change select in asp.net core

I have a Select on my View, and im trying every time that i change select call my controller and pass selected value as parameter
<form asp-controller="CompetitorsMarketplace" asp-action="Index" method="get" class="form-filters">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label class="control-label">Markeplace</label>
<select id="selectChangedValue" class="form-control" asp-for="MarketplaceName"
asp-items="Model.MarketplaceSelectList"></select>
</div>
</div>
<div class="col-md-3 text-left ">
<button class="btn btn-info btn-filter"><i class="fa fa-search"></i> Filtrar</button>
</div>
</div>
</form>
Controller
public IActionResult Index(CompetitorByMarketPlaceViewModel competitorByMarketPlaceViewModel, string textSearchMarketplace, int page = 1)
{
}
and what i try via javascript
<script language="JavaScript">
$('#selectChangedValue').on('change', function () {
var postData = document.getElementById("selectChangedValue").value;
// var post = { MarketplaceKey: postData};
window.location = "/CompetitorsMarketplace/Index?textSearchMarketplace=" + postData;
});
</script>
You can use Url.Action with Razor and fill your postdata with the .Replace jQuery function.
window.location = '#Url.Action("Index", "CompetitorsMarketplace", new { textSearchMarketplace = REPLACE })'.Replace('REPLACE',postData);

Set selected value of dropdowns from cookie

I have three dropdowns in my form, and I would like to not lose the data that the user has selected, even if I refresh or I navigate in other page and come back.
This is my view where I have the 3 dropdowns:
#using (Ajax.BeginForm("SearchForCars", "Home", null, new AjaxOptions { UpdateTargetId = "DivCategoriesTree", OnSuccess = "success", HttpMethod = "Post" }, new { make = "makes" }))
{
<div>
<div class="col-sm-4" style="height: 10em;display: flex;align-items: center ; padding-top:25px;">
<i class="fa fa-car" style="font-size:60px;color:red; padding-left:20px;"></i>
<strong style="padding-left:20px;">Vă rugăm să selectați vehiculul dumneavoastră!</strong>
</div>
<div class="col-sm-4">
<div style="padding-top:15px;">
<form class="form-control-static">
<div class="form-group">
<div class="row">
<div class="col-sm-10">
#if (ViewData.ContainsKey("makes"))
{
#Html.DropDownList("makes", ViewData["makes"] as List<SelectListItem>, "--Select car--", new { #class = "dropdown-toggle form-control" })
}
</div>
</div>
<div class="row">
<div class="col-sm-10">
<p></p>
#Html.DropDownList("models", new SelectList(string.Empty, "Value", "Text"), "--Select model--", new { #class = "dropdown-toggle form-control" })
</div>
</div>
<div class="row">
<p></p>
<div class="col-sm-10">
#Html.DropDownList("engines", new SelectList(string.Empty, "Value", "Text"), "--Select engine--", new { #class = "dropdown-toggle form-control" })
</div>
</div>
</div>
</form>
</div>
</div>
<div class="col-sm-4" style="height: 10em;display: flex;align-items: center ; padding-top:25px;">
<input type="submit" id="btnSearch" class="btn btn-default active" value="Cauta" disabled="disabled" style="width:150px;" />
</div>
</div>
}
</div>
Here are the 3 dropdowns:
I use cookies to store the data that the user has selected.
I tried to set the dropdown from the controller in this way:
public ActionResult Index()
{
var asa = HttpContext.Request.Cookies.Get("make_model_engine");
var model = asa.Values["model"].ToString();
var make = asa.Values["make"].ToString();
var makeList = new SelectList(makeRepository.GetMakes(), "ID", "Name");
ViewData["makes"] = makeList;
**var selected = makeList.Where(x => x.Value == make).First();
selected.Selected = true;**
return View();
}
Although it seems that the selected value is set correctly from cookies, it does not work, the dropdowns are not showing the selected value.
I guess that I should fix this in the view with javascript, but I'm new to javascript and I don't know what would be the best fix for this.
Can you please help me how can I resolve this?
Thank you!
You can pass the selected value you read from the cookie as the last parameter of the SelectList constructor:
var makeList = new SelectList(makeRepository.GetMakes(), "ID", "Name", make);

Asp.net MVC 5 : CRUD in modal dialog using javascript

I 'm newebie in Asp.net MVC 5
So , I have a simple project in which i'm usiong asp.net . I have an object named :
Object { Id, Code, Name} .
I want to list the Objects in grid , edit , add and remove .
I am able to show the list and add new object .
Those operations are in modal dialog .
I have some problems now :
How to send the Object to the action Controller then show it or edit itinto a modal dialog using javascript when i choose it ?
The second picture is when i click add new Object , it shows me the modal dialog , and all works fine with the Add , biut not with the others actions.
My Code
ObjectController :
public ActionResult AddObject()
{
if (Request.IsAjaxRequest())
return PartialView(dd);
return View(dd);
}
[HttpPost]
public ActionResult AddObject(ModelObject model)
{
/* Working Code */
}
AddObject partial View :
#using (Ajax.BeginForm("AddObject", "Object",
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "msgAdd",
OnSuccess = "addSuccess",
OnFailure = "addFailure"
},
new { #class = "form-horizontal" }))
{
#Html.ValidationSummary(true);
<div class="row" style="padding: 5px 0 5px 0">
<div class="col-lg-12">
<div class="col-lg-12 border no-margin" style="padding:10px 0px 10px 0 !important">
<div class="form-group" style="align-content:center">
<label class="col-sm-4 control-label">Code </label>
<div class="col-lg-6">
#Html.TextBoxFor(m => m.Code, new { #class = "form-control", placeholder = "Code" })
#Html.ValidationMessageFor(m => m.Code)
</div>
<label class="col-sm-4 control-label">Libellé </label>
<div class="col-lg-6">
#Html.TextBoxFor(m => m.Name, new { #class = "form-control", placeholder = "Libellé " })
#Html.ValidationMessageFor(m => m.Name)
</div>
</div>
</div>
</div>
</div>
<div class="hr-line-solid no-margin"></div>
<div class="row" style="padding: 5px 0 5px 0">
<div class="col-sm-1 col-sm-offset-4">
<button type="reset" class="btn btn-outline btn-primary"><i class="icon-refresh icon-white"></i> Réinitialiser</button>
</div>
<div class="col-sm-3 col-sm-offset-4">
<button type="reset" class="btn btn-default right" data-dismiss="modal">Annuler</button>
<input type="submit" value="Enregistrer" class="btn btn-success right" />
</div>
</div>
<div id="msgAdd" style="display:none">
</div>
}
</div>
ListObjects View :
<tbody>
#foreach (var m in Model.objects)
{
<tr class="gradeX">
<td id="idObject" style="display:none;"><span class="hideextra">#m.Id</span></td>
<td><span class="hideextra">#m.Code</span></td>
<td><span class="hideextra">#m.Name</span></td>
<td class="infont">
<center>
<a id="btnEdit"><i class="fa fa-pencil-square-o text-"></i></a>
<i class="fa fa-trash-o text-danger"></i>
<i class="fa fa-search text-navy"></i>
</center>
</td>
</tr>
}
</tbody>
Javascript :
1- For adding :
$(document).ready(function () {
//jQuery.noConflict();
$("#btn").click(function () {
var url = "AddObject"; // the url to the controller
$.get(url, function (data) {
$("#saisieJDiag").draggable({
handle: ".modal-header"
});
$("#saisieJDiag").resizable();
$("#saisieJDiag").html(data);
$("#saisieJDiag").modal("show");
$('#saisieJDiag').on('shown.bs.modal', function () {
$('.chosen-select', this).chosen();
});
$('.i-checks').iCheck({
checkboxClass: 'icheckbox_square-green',
radioClass: 'iradio_square-green',
});
});
});
});
</script>
Now I want the same approch but to edit and show the obecjt on the modal , how i can do that !

Form serialization always returns empty string

I have a dropdown in my view. Based on the selection, i insert a partial view into a div (placeholder) in view. Below is the View.
<div class="container">
<div class="row">
<div class="col-lg-4"><p class="lead">What do you want to do?</p></div>
<div class="col-lg-8">
<select id="myDropDown">
<option id="0" selected>I want to..</option>
<option id="1">Reset my password</option>
</select>
</div>
</div>
<div id="partialPlaceHolder" style="display:none;"> </div>
<script type="text/javascript">
$(document).ready(function () {
$('#myDropDown').change(function () {
/* Get the selected value of dropdownlist */
var selectedID = $(this).find('option:selected').attr('id');
/* Request the partial view with .get request. */
$.get('/Requests/FindPartial/' + selectedID, function (data) {
/* data is the pure html returned from action method, load it to your page */
$('#partialPlaceHolder').html(data);
/* little fade in effect */
$('#partialPlaceHolder').fadeIn('fast');
});
});
});
So when I select, "Reset my password" in the dropdown, I am successfully inserting my partial view into the div in my view. Below is my partial view.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-lg-12">
<div class="well well-lg" style="text-align:left">
<div class="form-horizontal" id="resetpasswordform">
<h4>Reset Password</h4>
<hr />
<div class="form-group">
#Html.LabelFor(model => model.ServersList, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ServerName, new SelectList(Model.ServersList))
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserName, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" id="submitButton" value="Reset" class="btn btn-default" />
</div>
</div>
</div>
</div>
</div>
</div>
}
<script>
$(function () {
$("#submitButton").click(function () {
debugger;
$.ajax({
type: "POST",
url: "Requests/Do_ResetPassword",
data: $("#resetpasswordform").serialize(),
success: function (data) {
debugger;
},
error: function (jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
});
});
</script>
The problem is when the submit button is clicked, and I make the ajax post call, the $("#resetpasswordform").serialize() is always "" (empty string).
I tried making the view just with one element. I verified that the elements have name attribute for serialize to work. I also confirmed that I don't have a type=submit in my button. I changed the resetpasswordform into a form instead of div. I even rendered the partial view directly in Index.cshtml without dynamically populating. Nothing fixed the problem. All the time it returns empty string.
I verified all other similar questions in SO and not getting any hint on what i am doing wrong. Please help.
How about you set the id in the form tag:
#using (Html.BeginForm("action", "controller", FormMethod.Post, new { Id = "resetpasswordform" }))
and remove it from the div.

incrementing a counter in asp mvc view page for inserting a field using jquery

I want to append a field based on the click event. I want to also increment the counter while doing this.
I currently have this:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "Create";
var i = 0;
}
Beginform code omitted
<div class="form-group">
#Html.LabelFor(model => model.Images[0].ImageUrl, htmlAttributes: new { #class = "control-label col-md-2" })
<div id="addhiddenimagefield">
</div>
<div id="counterincrement">
</div>
#*#Html.HiddenFor(model => model.Images[0].ImageUrl, new { id = "updateimageurl" })*#
<div class="col-md-10">
<input type="text" id="tbx-file-path" class="form-control" value="No file chosen..." readonly="readonly" />
<span class="btn btn-success fileinput-button">
<span>Select file...</span>
#*#Html.TextBoxFor(m => m.Images[0].ImageUrl, new { id = "fu-my-simple-upload", type = "file", name = "myfile" })*#
<input class="text-box single-line" type="file" name="myfile" id="fu-my-simple-upload" />
</span>
<div><a class="btn btn-primary" href="#" id="hl-start-upload">Start Upload</a></div>
</div>
</div>
This is my script code. Some of it is omitted to maintain the size of this question.
$("#hl-start-upload").on('click', function () {
$("#addhiddenimagefield").prepend('#Html.HiddenFor(model => model.Images[i].ImageUrl, new { id = "updateimageurl" })');
});
I want to increment the index counter "i" so that I can add more fields as the button is clicked. I've tried many ways but none have worked so far. Your help is greatly appreciated.
instead of using the Html.HiddenFor helper method, I wrote out the html in this way and use the client side to increment the variable like this:
$("#addhiddenimagefield").prepend('<input type="hidden" name="Images[#s].ImageUrl" id="updateimageurl" value="">'.replace('#s',String(i++)));

Categories