I want to use the string in "linktext" and pass it as a parameter into #Html.ActionLink. The reason I want to do this is to retrieve an object from my model
Example code in razor view:
#Html.ActionLink("One","MyAction","MyController",myDictionary[<myLinktextString>],null)
Basically I want myLinktextString to be "One" when I click the actionlink.
an example with a text field and a button click would be something like this
<input type="text" class="linkText" />
<input type="button" class="redirectLink" value="Redirect" />
in your script you would have
$('.redirectLink').on('click', function(){
var url = '#Url.Action("Action", "Controller", new { text = "0000" }';
url = url.replace("0000", $(".linkText").val());
window.location = url;
});
on the button click it will take the value of the text box and add it to a link and in this example redirect the user to that page. Let me know if you have any questions.
Related
I have a checkbox as follows:
#using (Html.BeginForm("ItemsEdit", "Items", FormMethod.Post))
{
#Html.CheckBox("itemCheck")
}
I want to be able to send an additional value to a controller when it is clicked, similar to something like this:
<input id = "#dataLineItem.Split(Model.ItemList.delimiterChar)[0]" type="checkbox" value="true" name="Remember" onclick="sendCheckId(this.id)" />
Below is the jQuery i am using to pass this id value to my controller:
function sendCheckId(checkedId) {
var sentId = checkedId;
$.post("/Items/ItemsEdit/", { sendIdToAction: sentId })
}
However, if i were to use the method above, i wouldnt know how to pass the 'true/false' values of the checkbox, to the same controller.
Maybe try onclick="sendCheckId(this.id,this.value)"
I'm not sure what that sendCheckId function leads to, but it should be pretty quick and easy to expand it to include the second value.
I found out that i could simply do this using the Razor engine:
#Html.CheckBox("itemCheck", new
{
onclick = "alert('Hello')"
}
Credit: https://www.c-sharpcorner.com/forums/how-to-call-on-click-event-in-mvc-5
(The answer by Ramesh Palanivel)
I have a button that when clicked, will change the value of the variable _name. But this doesn't work when I click Change Name then Refresh.
View
#{
var _name = ViewContext.RouteData.Values["name"].ToString();
}
<div>
<h1>Hello, #name!</h1>
<button type="button" onclick="#(_name = "John Doe")">Change Name</button>
<button type="button" onclick="location.href = '#Url.Action("MyAction", new { name = _name })'">Refresh</button>
</div>
Controller
public ActionResult MyAction(string name = "default") {
ControllerContext.RouteData.Values["name"] = name;
return View;
}
On refresh, the h1 should say "Hello, John Doe!". What is the right way of setting a variable inside HTML using Razor?
I think you are going in wrong direction. do this
put the name in a property in your model
create a hidden with Html.HiddenFor for name
change the value of hidden field with javascript on onClick
when the form is posted you have the new value of name in your model and you don't need new { name = _name } any more
instead of having name in your model and hiddenfor you can use this as alternative
Html.Hidden("name", ViewData("name"))
then for your link make url by this hidden value
Also using RouteData is not a good idea for your purpose, I would recommend to use ViewData["xxx"] instead
I've got a partial view that lists details about my entities. Details include a photo, caption, date, and name. There is an ActionLink for Delete that removes the item from the list.
I would like to make the Caption field an editable textbox to allow the user to edit the contents. Then I wold like to add an 'Update' link that will write this data to the DB. This is the only attribute that can be edited.
Basically I want to avoid the user having to open an 'Edit' form to change this field. I would like to be able to do it from within the list. Not sure how to create the 'Update' ActionLink, send it to the controller, and have the user-entered text available to the controller method.
The model that you pass to the view is of a certain type(of item in db). So, if You change the label with name "Caption" to a textbox of the same name, then the binding would remain the same - the output would be a textbox with the caption taken from the model passed to the View in Controller Action.
As for the update link:
I would create an Action of the same name as the View with [HttpPost] attribute and the model as parameter. The action would be invoked by a submit button in View (so all the labels and the textbox should be enclosed in a form). Inside that action perform the db update.
So:
The View should be something like this:
#model db.Foo
#using (Html.BeginForm()) {
<fieldset>
#Html.LabelFor(model=>model.Name)
(...)
#Html.TextBoxFor(model=>model.Caption)
<input type="submit" value="Update Caption"/>
</fieldset>
}
and the controller actions:
//The action that passes the model to the View
public ActionResult Details()
{
//
//get foo here
//
return View(foo); //Where foo is the item You use for your model
}
[HttpPost]
public ActionResult Details(foo model)
{
//
//Update model here with model of type foo
//
}
Hope this helps
Since it seems to be an extremely basic edit, I would just put the Caption in a Div then using CSS/jQuery display an edit button (glyphicon glyphicon-pencil) on mouseover. On click set the Div to Editable (use styling to show it's in edit mode, and only exit edit mode with a save button). On save, do a jQuery Ajax call to update the value in the database.
Please be extra cautious to not have any SQL Injection Attacks as editable content could contain anything from a user.
CSS might look like:
.editor editor-display button
{
display: none;
}
.editor editor-display:hover .edit-button
{
display: inline-block;
}
.editor editor-edit .edit-button
{
display: none;
}
.editor editor-edit .save-button
{
display: inline-block;
}
Html might look like:
<div class="my-entity editor editor-display" data-id="5" >
<div class="edit-content">#model.Caption</div>
<button id="edit-caption-button" class="edit-button" />
<button id="save-caption-button" class="save-button" />
<div>
Javascript might look like:
$(document).ready(function()
{
$("#save-caption-button").on("click", function()
{
$(this).parent("editor").removeClass("editor-display").addClass("editor-edit");
});
$("#save-caption-button").on("click", function()
{
$.ajax({
url: "/MyEditity/UpdateCaption",
data: { id: $(this).parent(".my-entity").data("id"),
caption: $(this).parent(".my-entity").find(".edit-content").first().text() };
});
$(this).parent("editor").removeClass("editor-edit").addClass("editor-display");
});
});
Controller:
public ActionResult UpdateCaption(int id, string caption)
{
// lookup entity by id
// change caption value
// save
return new EmptyResult();
}
This is a super basic (UNTESTED!) example, with no exception handling.
I'm pretty much a jquery newb...I've almost got this working I think, let me know if i can clarify anything.
I have a screen displaying a list..let's call them affiliates. To create a new affiliate, a modal style pop up dialogue is used.
When the dialogue "Create" button is clicked, the form data must be saved (creating a new affiliate), the dialogue disappears, and the affiliate list updates without reloading the page
The jquery file at the bottom shows how I'm trying to do it now: trying to detect a click on the "confirm" button, get the form to submit using the data target property, and using the form's target property to know what container to update.
What is happening is: nothing. The cancel button works, create button does absolutely nothing.
Also note that the "Create" button, which will act as the form's submit, is not located within the <form> tags.
I'm pretty sure I'm doing modals wrong but let's ignore that for the moment and focus on the async post and list update. I've included my relevant code below to support my post.
--AffiliateListPartial
#model IPagedList<Acme.Business.DomainModel.Affiliates.Affiliate>
<div class="items-list" id="affiliate-list-view">
#foreach (var item in Model)
{
<a href="#Url.Action("AffiliateDetails", "Vendor", new { id = item.AffiliateId })">
//basic spans and razor display list in here..nothing notable
</a>
}
</div>
The above partial view is contained within a full view, lets call it AffiliateList. Nothing particularly relevant in there except that it is controlled by the VendorController/Affiliatelist method.
The VendorController.AffiliateList looks like:
public ActionResult AffiliateList(string searchTerm = null, int page = 1)
{
var userId = WebSecurity.GetUserId(User.Identity.Name);
var model = (from a in db.Affiliates.ToList()
where a.VendorId == userId
select a).ToPagedList(page, 15);
if(Request.IsAjaxRequest()) return PartialView("_AffiliateListPartial", model);
return View(model);
}
The modal style dialoque for creating a new affiliate (I'll just include the lines that I think are relevant):
_Modal.AffiliateCreate.Partial
<form id="affiliate-create-form" class="form" method="post" action="#Url.Action("AffiliateCreate")" data-acme-ajax="true" data-acme-target="#affiliate-list-view">
// multiple input elements
</form>
<div class="modal-footer">
<button name="close_modal"><span>Cancel</span></button>
<button name="confirm" data-acme-target="#affiliate-create-form"><span>Create</span></button>
</div>
And the VendorController.AffiliateCreate method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AffiliateCreate(Affiliate affiliate)
{
if (!ModelState.IsValid) return View(affiliate);
db.Affiliates.Add(affiliate);
db.SaveChanges();
return RedirectToAction("AffiliateList");
}
And the .js file's relevant parts:
$("button[name='confirm']").on("click", function() {
var $form = $(this).attr("data-acme-target");
var options = {
url: $form.attr("action"),
type: $form.attr("type"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-acme-target"));
var $newHtml = $(data);
$target.replaceWith(data);
$newHtml.effect("highlight");
});
$(".modal_overlay").css("opacity", "0");
$(".modal_container").css("display", "none");
return false;
});
$("button[name='close_modal']").on("click", function(event) {
$(".modal_overlay").css("opacity", "0");
$(".modal_container").css("display", "none");
return false;
});
var $form = $(this).attr("data-acme-target"); is getting the attribute named 'data-acme-target' of the button, rather than the form it's associated with. So then when you're using $form.attr('action'), you aren't getting anything back.
Since data-acme-target is an ID to another control that is the form you want to submit, use $($(this).attr("data-acme-target")); to get it.
If i have a form which action should differ according to some session variable . How can i change the action of the form dynamically so that on client click of specific link button i could submit the form with the required action.
<form id="myform" action="I wanna to change it dynamically" method="post" >
<%-------------%>
</form>
<script type="text/javascript">
function submitform()
{
document.myform.submit();
}
</script>
For example :
If session["emp"] = 1 then the action is /A.aspx
If session["emp"] = 2 then the action is /B.aspx
Option 1
I typically place server values in hidden fields when the form loads so that I can interact with them in JavaScript:
function submitform()
{
// Get URL that was set server-side for form submission
var myHiddenObj = document.getElementById("<%= hdnServerValue.ClientID %>");
// Get form object
var myFormObj = document.getElementById("myform");
// Change form action & submit
myFormObj.action = myHiddenObj.value;
myHiddenObj.submit();
}
Option 2
If you simply want the form action to change and require no other client-side processing, simply change the form action on the server (you'll need to add runat="server" to your form tag):
Markup:
<form id="myform" runat="server" action="" method="post" >
<%-------------%>
</form>
C# (or your preferred server side language)
if(Session["emp"].ToString() == "1")
myform.Action = "A.aspx";
else if (Session["emp"].ToString() == "2")
myform.Action = "B.aspx";
else
// Handle neither 1 or 2
Try this
if(condiotion1)
form1.Attributes.Add("action", "My Action1");
else if(condiotion2)
form1.Attributes.Add("action", "My Action2");