I have a text box in view and 2 action link in the same form. what I want to do this that when I click action links textbox value will get in ActionResult
Html.BeginForm("downloadpage","Finance"){
<div class="col-5">
<input type="text" class="form-control" name="txttitle" id="txtval" placeholder="E.g. PAK10NOV18" />
#Html.TextBox("first_name")
</div>
#Html.ActionLink("Download Master File", "get_master_file");
#Html.ActionLink("Download IBFT File", "get_ibft_file");
}
backend
public ActionResult get_master_file(string txttitle)
{
return View();
}
public ActionResult get_ibft_file(string txttitle)
{
return View();
}
Why don't you use jquery and an ajax call?
Have a button that when you click calls a javascript function. In here you can get the value of the input such as this:
var textvalue = $("#txtval").val();
Create a json such as this:
var json = '{txttitle: "' + textvalue + '"}';
and call your controller such as this:
$.ajax({
url:'#Url.Action("//Function", "//Controller")',
type:'POST',
data: json,
contentType:'Application/json',
success:function(result){
//Do nothing or do whatever you want
}
});
Related
I am trying to pass value from cshtml hidden field to Controller when calling Url.Action method
cshtml
#using (Html.BeginForm())
{
<div id="content">
<input type="hidden" name="currentID" id="currentID" />
<div>#Url.Action("ClaimBudgetHdSubPartial")</div>
</div>
}
javascript
function validateAndNextStep1() {
var rowKey = GVClaimBudgetHd.GetRowKey(visibleIndex);
$("#currentID").val(rowKey);
}
controller
[Route("ClaimBudgetHdSubPartial")]
public ActionResult ClaimBudgetHdSubPartial()
{
//Try to get hidden field "currentID" in this controller
//Tried to use Request.Params["currentID"] but result is null
return PartialView("~/Views/ClaimBudgetHdSubPartial.cshtml");
}
This tutorial shows you how to use Form in MVC:
https://www.aspsnippets.com/Articles/ASPNet-MVC-HtmlBeginForm-Tutorial-with-example.aspx
I have an MVC site, and I use the same "_layout page" for all the view.
In _layout page, I have a select control.
What I want is to read the selected value of the control from the other pages.
Can you help me understand how to do?
Edit:
_Layout.cshtml
<div class="col-sm-4 col-xs-6">
<label class="col-sm-2 control-label" for="slt_Aziende">Azienda:</label>
<select id="mySharedSelectControl">
<option value="1">value 1</option>
<option value="2">value 2</option>
</select>
</div>
Index.cshtlm (using _Layout.cshtml)
#model IEnumerable<MySite.Models.MyModel>
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
MyModelController
public class MyModelController : Controller
{
public ActionResult Index()
{
//get value from mySharedSelectControl from Layout page
var selectedValueFromLayoutPage;
//do something
return View();
}
}
Based on what #Mairaj said is right i.e you can't directly read values of controls in your controller.
What you can do is create a JavaScript function like this:
$(document).ready(function () {
$("#mySharedSelectControl").change(function () {
var dropdownValue = $(this).val();
$.ajax({
url: "#Url.Action("PutValueinSession", "MyModel")", //Action method on which you want to send this dropdown value
data: { id: dropdownValue },
success: function (e) {
window.location = window.location;
}
});
});
});
You can create a method in which you can put this value in session and used across your whole page like below:
public JsonResult PutValueinSession(int id)
{
Session["DropdownControlValue"] = id;
return Json(new { Result = "" }, JsonRequestBehavior.AllowGet);
}
Now you can access this value on any page:
public ActionResult Index()
{
//get value from mySharedSelectControl from Layout page
var selectedValueFromLayoutPage=Session["DropdownControlValue"];
//do something
return View();
}
You can't directly read value of controls in Controller, you need to send the value of dropdown to the controller and than process what you want.
Or you can directly read value of dropdown from JavaScript in other views and do your processing.
I have a sort of Master-Detail Edit form and I'm trying to follow this post: Using Ajax... to get the partial view to postback.
My Edit form has a partial view that has a list of sub items, and another partial create view in it to add new items. I'd like the partial create view to post back and update the list without refreshing the whole page if possible.
Here's what I have so far:
MyController.cs -
public ActionResult Edit(int? id)
{
//...
ViewBag.CustomFormId = id;
using (var _db = new MkpContext())
{
//...
return View(profileEdit);
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CustomForm editForm)
{
//...
if (!ModelState.IsValid) return View(editForm);
using (var _db = new MkpContext())
{
var form = _db.CustomForms.Find(editForm.CustomFormId);
//...
_db.Entry(form).State = EntityState.Modified;
_db.SaveChanges(User.ProfileId);
return RedirectToAction("Index");
}
}
public ActionResult _CustomFieldList(int id)
{
ViewBag.CustomFormId = id;
using (var _db = new MkpContext())
{
var formCustomFields = (from cf in _db.CustomFields
where cf.CustomFormId == id
select cf);
return PartialView(formCustomFields.ToList());
}
}
// Nested in _CustomFieldList
public ActionResult _CustomFieldCreate(int id)
{
var newField = new CustomField
{
CustomFormId = id
};
return PartialView(newField);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult _CustomFieldCreate(CustomField addField)
{
ViewBag.CustomFormId = addField.CustomFormId;
if (ModelState.IsValid)
{
using (var _db = new MkpContext())
{
_db.CustomFields.Add(addField);
_db.SaveChanges();
}
var newField = new CustomField
{
CustomFormId = addField.CustomFormId
};
return PartialView(newField); // Probably need to change this somehow
}
return PartialView(addField);
}
And the views:
Edit.cshtml -
#model PublicationSystem.Model.CustomForm
#{
ViewBag.Title = "Edit Custom Form";
Layout = "~/Views/Shared/_LayoutSmBanner.cshtml";
}
<div class="form-horizontal">
<div class="row">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#* Fields for this form *#
}
<div id="CustomFields" class="col-md-6">
#Html.Action("_CustomFieldCreate", new { id = ViewBag.CustomFormId })
</div>
</div>
</div>
<script>
$(function () {
$("#createFieldForm").on("submit", function (e) {
e.preventDefault(); //This prevent the regular form submit
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$("#CustomFields").html(result);
}
});
return false;
});
});
</script>
_CustomFieldCreate.cshtml -
#model PublicationSystem.Model.CustomField
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div id="result"></div>
<div class="form-horizontal">
<h4>CustomField</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model =>model.CustomFormId)
<div class="row">
#* Fields for the form *#
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div id="customFieldList">
#Html.Action("_CustomFieldList", new { id = ViewBag.CustomFormId })
</div>
_CustomFieldList.cshtml
#model System.Collections.Generic.IEnumerable<PublicationSystem.Model.CustomField>
<table class="table">
#* List table code *#
</table>
Edit: I rewrote the pages so that the list is part of the create partial view. What happens now is, if you enter data for _CustomFieldCreate and press submit, the first time, it refreshes just that view (including the nested list view). However the second time, it redirects to the view, probably because the first refresh didn't rebind the javascript to the submit button. Also, the Create view doesn't clear out the fields, but persists the originally entered data.
You will need a form in your partial view whose submit action binds to a javascript function that posts to your controller.
For example if your form id is MyForm:
$('#MyForm').on('submit', function (e) {
e.preventDefault(); //This prevent the regular form submit
$.ajax({
url: $(this).action, // This will submit the post to whatever action your form goes to
type: "POST", // This tells it that it is a post
data: $(this).serialize(), // This sends the data in the form to the controller
success: function (data) {
// do some javascript on success
},
error: function (xhr, ajaxOptions, thrownError) {
// do some javascript on error
}
});
});
This javascript overrides the default form submit and does an ajax post to your controller and then returns with success or error where you can do anything you want.
Here is some jquery ajax documentation:
http://api.jquery.com/jquery.ajax/
You should look into using AJAX. That should accomplish what I think you are describing. You'll want to create a javascript function that handles the submit event on the form, then post the form data to some create action in your MVC app using AJAX. If you are using jQuery, the library makes it pretty simple.
http://api.jquery.com/jquery.ajax/
We have one Parent Page (DistributionReview.aspx) and it is having two tabs (DistributionByType and DistibutionByStatus).
The parent page is having a datetime textbox and trying to pass this date to the partialviewresult.
Wondering how to pass this data to the partialview?
<div id="container" >
<div> Select a Date:
<input type="text" id="fileDepositDate" name="datepicker" /></div>
<div id="divDistributionReview">
<ul>
<li>Distribution Type</li>
<li>Status</li>
</ul>
</div>
public ActionResult DistributionReview(string id)
{
var view = View(ApplicationConstants.DistributionReviewViewName, new MegaLockbox.Web.ViewModels.DistributionByTypeViewModel(securityManager, distributionReviewDataAdapter, id));
return view;
}
[HttpPost]
public ActionResult DistributionByType(string id)
{
var view = PartialView(ApplicationConstants.DistributionByTypeViewName, new MegaLockbox.Web.ViewModels.DistributionByTypeViewModel(securityManager, distributionReviewDataAdapter, id));
return view;
}
attach a click event handler to the links and pass the date in Query String.
e.g. you can do such thing using jQuery like >
$("a").click(function () {
addr = $(this).attr("href");
$(this).attr("href", addr + "?SelectedDate=" + $("#fileDepositDate").val();
});
and include Date SelectedDate in the Partial View Controller parameters
I am using ASP.NET MVC 2. I have a modal dialog (done through jquery UI) that contains two text boxes and a button. All the controls are inside a form.
I would like to invoke, when the user click the button, a controller action that do some operations on the passed data contained in the two text boxes and then return an integer value and a string message to the user.
Could anybody provide an example for doing this with jquery?
Thanks so much!
suppose you have the following form :
<form id="ajax-form">
<fieldset>
<input type="text" id="firstname" name="firstname" />
<input type="text" id="lastname" name="lastname" />
<input type="submit" value="send" />
</fieldset>
</form>
using jQuery
$(document).ready(function(){
$("#ajax-form").submit(function(){
$.ajax({
type: "POST",
url: "Person/Add",
data: $("#ajax-form").serialize(),
success: function (response) {
// whatever you want to happen on success
},
error: function (response) {
alert('There was an error.');
}
});
});
});
Accessing Your Data in the Action Method.
public ActionResult Add(FormCollection form)
{
string firstname = form["firstname"];
string firstname = form["lastname"];
// do whatever you want here
// then return something to the view
return Json(/*some object*/);
}
another way is to use Microsoft Ajax
<% using (Ajax.BeginForm("Add", "Person",
new AjaxOptions() {
UpdateTargetId = "formDiv",
InsertionMode = InsertionMode.Replace,
HttpMethod = "Post" })) {%>
<fieldset>
// Form Elements Here.
</fieldset>
<% } %>
UpdateTargetId is the id of the html element to be targeted.
The InsertionMode option has three values Replace, InsertAfter, InsertBefore
Hope that was helpful
Update : you don't have to return a Json result in your action method you can simply return a partial view or any HTML code as the response object and then insert it using jQuery.
You may take a look at the documentation about how you could implement a dialog that contains form fields. And when the confirm button is clicked you could simply send an AJAX request.
buttons: {
Confirm: function() {
// read the value in the textbox
var name = $('#name').val();
// send an AJAX request to an action that will return JSON:
$.getJSON('/home/foo', { name: name }, function(result) {
// read the returned value
alert(result.Value);
});
},
Cancel: function() {
$(this).dialog('close');
}
}
And your controller action:
public ActionResult Foo(string name)
{
return Json(new { Value = '123' }, JsonRequestBehavior.AllowGet);
}