MVC button click call POST Action method - c#

How can I call an MVC action method with complex parameters, like the below, from a button click event?
[ValidateInput(false)]
[HttpPost]
public ActionResult Export(ViewModel vm)
{
// some logic
}
I have made it a POST action because I need to pass HTML tags of the current page on which the button is to the action method which is too long. I have tried this but this its for a GET operation
<input type="button" value="Detail" onclick="location.href='#Url.Action("Export", "Report")?html=' + $('#test').html()" />

If you want to do this using a button click you can subscribe the to click event of the button in JS. In your JS, you can do an ajax post, which will post a JSON object (your VM) to your action:
Razor:
<input type="button" value="Detail" id="buttonId" />
JS:
$('#buttonId').click(function () { //On click of your button
var property1 = $('#property1Id').val(); //Get the values from the page you want to post
var property2 = $('#property2Id').val();
var JSONObject = { // Create JSON object to pass through AJAX
Property1: property1, //Make sure these names match the properties in VM
Property2: property2
};
$.ajax({ //Do an ajax post to the controller
type: 'POST',
url: './Controller/Action',
data: JSON.stringify(JSONObject),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
Another way to do this is submit the view model using a form.
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.PropertyName1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="text" id="PropertyName1" name="PropertyName1" class="form-control" />
#Html.ValidationMessageFor(model => model.PropertyName1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PropertyName2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PropertyName2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PropertyName2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Button text" class="btn btn-primary" />
</div>
</div>
</div>
}

You can do that with HTML form
<form action="#Url.Action("Export", "Report")" method="POST">
<input type="hidden" name="html" value="ADD YOUR HTML HERE">
<input type="button" value="Detail" />
</form>
And inside your controller you need to use html parameter
[ValidateInput(false)]
[HttpPost]
public ActionResult Export(ViewModel vm, string html)
{
// some logic
}

try this
<form action="#Url.Action("Export", "Report")" method="POST">
<input type="hidden" name="html" id="html" value="ADD YOUR HTML HERE">
<input type="button" id="btn1" value="Detail" />
</form>
add Script in js
$("#btn1").click(function(){
$("#html").val($('#test').html());
})
add param in your method string html

Related

more than 1 HttpPost is activating

I am making a page where I'd like to be able to have several different actions happening depending on what is being done.
for instance I have a dropdown where I want different forms to be loaded in to the page depending on the selection in the dropdown.
Currently I'm doing it like this:
$(document).ready(function () {
$('#subject').on("change", function (e) {
e.preventDefault();
var selectedVal = $('#subject').val();
$.ajax({
url: "ContactUs/GetForm",
type: "POST",
data: { searchValue: selectedVal },
async: true,
success: function (data) {
$('#renderForms').empty();
$('#renderForms').append(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("An error has occured!!! " + xhr.status + " && " + xhr.responseText);
}
});
}; etc...
this hits the following method no problem
[HttpPost]
public ActionResult GetForm(string searchValue)
{
//my code here
return PartialView("_Bills",contactModel.contactBillsModel);
}
However when I click on it also hit the following method which is not my intention.
[HttpPost]
public ActionResult Index(Contact_Portal.Models.ContactViewModel contactModel)
{
return View(contactModel);
}
How do I prevent this behaviour ?
the last HttpPost I'm using in a button in the partial page like this
<input id="Send" type="submit" value="Send" class="btn btn-default" />
Edit:
Adding Additional Information per requested.
the view with the dropdown
#model WebPortal.Models.FormViewModel
#{
ViewBag.Title = "multiple forms";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>multiple forms</h2>
<label>My selection is... </label>
#Html.DropDownListFor(model => model.contactSelectListItems, new List<SelectListItem>
{
new SelectListItem() {Text = "option 1", Value="option 1"},
new SelectListItem() {Text = "option 2", Value="option 2"},
new SelectListItem() {Text = "option 3", Value="option 3"},
new SelectListItem() {Text = "option 4", Value="option 4"}
}, "--choose--", new { id = "subject", #class="dropdown-item"})
<div id="renderForms">
</div>
one of the views with the forms:
#model WebPortal.Models.AformViewModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>A Form</h4>
<hr />
<div id="InfoBox" class="form-group col-md-20">
Remember to fill out this text with relevant text.
</div>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="container">
<div class="row">
<div class="form-group form-group-sm col-sm-6">
<div class="row">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-sm-9">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group form-group-sm col-sm-6">
<div class="row">
#Html.LabelFor(model => model.Phone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-sm-9">
#Html.EditorFor(model => model.Phone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group form-group-sm col-sm-6">
<div class="row">
<div class="col-sm-9">
<!--#Html.Action("Index", "ContactUs")-->
<input id="Send" type="submit" value="Send" class="btn btn-default" />
</div>
</div>
</div>
</div>
</div>
</div>
Well I have a solution thou I'm not really happy with it but it works.
this is what I've done since posting my question:
I've changed on request from Stephen Muecke this part here:
<div class="form-group form-group-sm col-sm-6">
<div class="row">
<div class="col-sm-9">
<!--#Html.Action("Index", "ContactUs")-->
<input id="Send" type="submit" value="Send" class="btn btn-default" />
</div>
</div>
</div>
to
<div class="form-group form-group-sm col-sm-6">
<div class="row">
<div class="col-sm-9">
<input id="Send" type="submit" value="Send" class="btn btn-default" />
</div>
</div>
</div>
and after that It removed my problem with activating both my HttpPost Actions GetForm and Index(viewmodel)
but I got the new problem of the submit button activating the GetForm action instead of the Index(viewmodel) action.
So because of this I changed my submit button to the following
<input id="Send" type="submit" value="Send" formaction=#Url.Action("Index","ContactUs") class="btn btn-default" />
this change solved my problem for now but I feel that the input submit button now is now not inline with the ideas behind unobtrusive event handling.
Edit:
instead of the above submit button line I added this to the html form:
#using (Html.BeginForm("Index", "ContactUs"))
The problem is that your input with type="submit" is submitting the form. This is the standard behaviour for HTML-forms.
Change the input's type to type="button":
<input id="Send" type="button" value="Send" class="btn btn-default" />
Then change the event in jQuery to "click":
$(document).ready(function () {
$('#subject').on("click", function (e) {
e.preventDefault();
var selectedVal = $('#subject').val();
$.ajax({
url: "ContactUs/GetForm",
type: "POST",
data: { searchValue: selectedVal },
async: true,
success: function (data) {
$('#renderForms').empty();
$('#renderForms').append(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("An error has occured!!! " + xhr.status + " && " + xhr.responseText);
}
});
}; etc...

Html.BeginForm FormMethod.Post submit button click not working?

Single page having three different registration form,based on single ID reference, I need to call the three different [HttpPost] ActionResult method ,when i click the submit button for first form it's goes to first action result method correctly.
<div class="page-content">
<div class="container-fluid">
<header class="section-header">
<div class="tbl">
<div class="tbl-row">
<div class="tbl-cell">
<h2>Company Registration Form</h2>
</div>
</div>
</div>
</header>
#using (Html.BeginForm(FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<section class="tabs-section">
<div class="tabs-section-nav tabs-section-nav-icons">
<div class="tbl">
<ul class="nav" role="tablist">
<li class="nav-item">
<a class="nav-link active" href="#tabs-1-tab-1" role="tab" data-toggle="tab">
<span class="nav-link-in">
<i class="font-icon font-icon-cogwheel"></i>
Company Registration Form
</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#tabs-1-tab-2" role="tab" data-toggle="tab">
<span class="nav-link-in">
<span class="glyphicon glyphicon-music"></span>
Company Social Network
</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#tabs-1-tab-3" role="tab" data-toggle="tab">
<span class="nav-link-in">
<i class="fa fa-product-hunt"></i>
Company Reference
</span>
</a>
</li>
</ul>
</div>
</div><!--.tabs-section-nav-->
<div class="tab-content">
<div role="tabpanel" class="tab-pane fade in active show" id="tabs-1-tab-1">
<br />
<br />
<section>
<div>
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model =>Model.company.CompanyName, new { #class = "form-label semibold control-label" })
#Html.TextBoxFor(model => model.company.CompanyName, new { #class = "form-control", placeholder = "Enter the Company Name" })
#Html.ValidationMessageFor(model => model.company.CompanyName)
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.ShortName, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.ShortName, new { #class = "form-control", placeholder = "Enter the Short Name" })
#Html.ValidationMessageFor(model => model.company.ShortName)
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.Division, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.Division, new { #class = "form-control", placeholder = "Enter the Division" })
#Html.ValidationMessageFor(model => model.company.Division)
</fieldset>
</div>
</div><!--.row-->
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.Email, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.Email, new { #class = "form-control", placeholder = "Enter your Email" })
#Html.ValidationMessageFor(model => model.company.Email)
</fieldset>
</div>
</div><!--.row-->
</div>
</section>
<input type="submit" name="Submit" id="Save" value="Save" class="btn btn-rounded btn-inline btn-success" onclick=" GetInfo();" />
</div><!--.tab-pane-->
<div role="tabpanel" class="tab-pane fade" id="tabs-1-tab-2">
<br />
<section>
<div>
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.CompanySocial.FaceBookID, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.CompanySocial.FaceBookID, new { #class = "form-control", placeholder = "Enter the Facebook Link" })
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.CompanySocial.TwitterID, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.CompanySocial.TwitterID, new { #class = "form-control", placeholder = "Enter the Twitter Link" })
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.CompanySocial.linkedinID, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.CompanySocial.linkedinID, new { #class = "form-control", placeholder = "Enter the Linkedin Link" })
</fieldset>
</div>
</div><!--.row-->
</div>
</section>
<input type="submit" name="Submit" value="Previous" class="btn btn-rounded btn-inline btn-primary prev-step" />
<input type="submit" name="Submit" id="Save" value="Next" class="btn btn-rounded btn-inline btn-success" onclick="GetInfo1();" />
</div><!--.tab-pane-->
<div role="tabpanel" class="tab-pane fade" id="tabs-1-tab-3">
Tab 3
<br /><br />
<input type="submit" name="Submit" value="Previous" class="btn btn-rounded btn-inline btn-primary prev-step" />
<input type="submit" name="Submit" value="Finish" class="btn btn-rounded btn-inline btn-success" />
</div><!--.tab-pane-->
</div><!--.tab-content-->
</section><!--.tabs-section-->
}
</div>
</div>
ActionResult Code:
[HttpPost]
public ActionResult AddCompany(MainModel cmp)
{
try
{
if (ModelState.IsValid)
{
}
return View();
}
catch
{
return View();
}
}
When i click second Submit button it's again going to the same ActionResult AddCompany(MainModel cmp) but i need to go to ActionResult AddSocial(MainModel Social)
Here this code :
[HttpPost]
public ActionResult AddSocial(MainModel Social)
{
try
{
if (ModelState.IsValid)
{
//ScriptManager.RegisterStartupScript(this, typeof(Page), "paginationClickHandler", "paginationClickHandler();", true);
}
return View();
}
catch
{
return View();
}
}
Ajax Method:
function GetInfo() {
var company = { companyName: document.getElementById('CompanyName').value, shortName: document.getElementById('ShortName').value, division: document.getElementById('Division').value, Email: document.getElementById('Email').value }
$.ajax({
type: "POST",
url: "/Company/AddCompany",
data: '{cmp:' + JSON.stringify(company) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
function GetInfo1() {
var Social = { faceBook: document.getElementById('FaceBook').value, twitter: document.getElementById('Twitter').value, linkedin: document.getElementById('linkedin').value }
$.ajax({
type: "POST",
url: "/Company/AddSocial",
data: '{Social:' + JSON.stringify(Social) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
Your button is still inside a form. So when you handle your button click in javascript, you need to make sure to prevent the default behavior of a submit button click inside a form ( the form submit).
Using unobtrusive javascript way, give a unique id to your button
<input type="submit" id="saveSocial" value="Next" />
and now, bind click event on this button, prevent the default behavior using
jquery preventDefault method and call your js method.
$(document).ready(function() {
$("#saveSocial").click(function(e) {
e.preventDefault();
GetInfo1();
});
});
Also it does not make sense to return a full view from your action method when the call is from ajax code. May be you should return a json response.
A submit inside the form is going to post the form, even if you have an onclick action written. If you want it to instead call the javascript function, change the <input> to a <button> or <a> tag.
EDIT
Delete the form tag completely to prevent submission which is reloading your page.

c# mvc form: how to build view for simple feedback form leveraging the benefit of using html.editorfor?

I have simple input form (basically for feedback) with following fields:
Name, Gender, Mobile-Number, Complaint text. (To simplify I am not mentioning any POST action OR submit button on the form)
Currently, I have created following MVC structure:
public class ComplaintController
{
[HttpGet]
public ActionResult Index()
{
return View(); //This view displays the complaint form with all above fields
}
}
I read this and several other links where they suggest to use #Html.EditorFor as it creates UI based on model data-type.
Currently, I am not passing any model to the [HttpGet] view. If I want to use #Html.EditorFor, I need to pass my model to [HttpGet] Index View, how can I do that? What is best pratise to create such MVC forms?
Your Controller:
public ActionResult Index()
{
whateverModel d = new whateverModel();
return View(d);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(whateverModel m)
{
if (ModelState.IsValid)
{
//its valid, update your database or do soemthing useful here
return RedirectToAction("Success");
}
//its not valid reload the page and let data annotations show the error
return View(m);
}
Once you have your code in the controller then you can have visual studio auto-create your view. In your controller, right click the "d" in return View(d); and select "Add View." Change the Template to "create" and Model class to your Model (whateverModel in this example). It will auto generate the chtml page for you with the model imported and the editors already generated for you. Example auto generated view below. The you can work on styling and such.
cshtml:
#model YourSolution.Models.whateverModel
#{
ViewBag.Title = "Whatever";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Whatever</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Whatever</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.FriendlyName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FriendlyName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FriendlyName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Order, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Order, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Order, "", new { #class = "text-danger" })
</div>
</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>
#Html.ActionLink("Back to List", "Index")
</div>
Currently, I am not passing any model to the [HttpGet] view. If I want
to use #Html.EditorFor, I need to pass my model to [HttpGet] Index
View, how can I do that?
Hi sahil ,As a first step , create one model class like below
public class FeedBack
{
public string Name{get;set;}
public string Gender{get;set;}
public int Mobile-Number{get;set;}
public string Complaint{get;set;}
// other additional fields
}
And in the controller get method ,pass a model like below
public class ComplaintController
{
[HttpGet]
public ActionResult Index()
{
FeedBack OBJFeedback = new FeedBack();
return View(OBJFeedback);
}
}
And in a view , strongly type this model and post the data as you want to the controller post methods.
Here is the example of strongly typed view : http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/strongly-typed-views-in-mvc/
Important Note : In the get action method , since you dont want to display any values by default in the view , even if you dont pass model object it will work in the same way.
Hope the above information was useful
Thanks
Karthik
If you want to use #Html.EditorFor, then you mast pass the model to the view.What does #Html.EditorFor do? It makes the html tag like
<input class="text-box single-line" id="Name" name="Name" type="text" value="">
So if you do not want to pass the model to the view then you need to write the raw html tag like above. It is important to keep the html tag's name property same as the mvc's model property because when you want to post the data to the controller the name property of the html tag will map the mvc model property and get the corresponding value at the Controller method.
At the view(somthing.cshtml) you can use html tags, because .cshtml==.cs+html . So the whole code look like
Controller methods
public ActionResult FeedBack()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult FeedBack(FeedBackModel Model)
{
var feedBack = Model;
return View();
}
And the View
<form action="/Home/FeedBack" method="post" id="feedBackForm">
#Html.AntiForgeryToken()
<hr>
<div class="form-group">
<div class="col-md-5">
<label for="Name">Name</label>
</div>
<div class="col-md-5">
<input class="text-box single-line" name="Name" type="text">
</div>
</div>
<div class="form-group">
<div class="col-md-5">
<label for="Name">Gender</label>
</div>
<div class="col-md-5">
<select name="Gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-md-5">
<label for="Name">MobileNumber</label>
</div>
<div class="col-md-5">
<input class="text-box single-line" name="MobileNumber" type="text">
</div>
</div>
<div class="form-group">
<div class="col-md-5">
<label for="Name">Complaint</label>
</div>
<div class="col-md-5">
<textarea class="text-box single-line" name="Complaint"></textarea>
</div>
</div>
<div class="col-md-5">
<input type="submit" value="Create" class="btn btn-default">
</div>
</form>
If you do not want to use submit then you can use ajax.

Popup partial view in a bootstrap model popup

#Html.ActionLink("edit", "Edit", "MedQuantityType", new { id = item.Med_quan_typeId }, new
{
#* Needed to link to the html of the modal*#
data_target = "#mymodel",
#* Tells the bootstrap javascript to do its thing*#
data_toggle = "modal",
})
This the action link I try to popup partial view in bootstrap model, it's working fine when I try to edit & save it works except model state is not valid
here my controller code
public async Task<ActionResult > Edit([Bind(Include = "Med_quan_typeId,Med_quan_type,Med_quantity")] Med_quantity_type med_quantity_type)
{
if (ModelState.IsValid)
{
db.Entry(med_quantity_type).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return PartialView(med_quantity_type);
}
If my model state fails the controller return partial view but its not popup in mymodel this is my partial view cshtml page
<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">Medicine Quantity Type - Edit</h4>
</div>
<div class="modal-body">
#using (Ajax.BeginForm("Edit", "MedQuantityType",
new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "mymodel"
}))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.Med_quan_typeId)
<div class="form-group">
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.Med_quan_type, new { #class = "control-label " })
</div>
<div class="col-md-6">
#Html.TextBoxFor(model => model.Med_quan_type, new { #class = "form-control", #id = "txtquantype" })
#Html.ValidationMessageFor(model => model.Med_quan_type)
</div>
</div>
<div class="form-group">
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.Med_quantity, new { #class = "control-label" })
</div>
<div class="col-md-6">
#Html.TextBoxFor(model => model.Med_quantity, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Med_quantity)
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" value="Save" class="btn btn-success" id="btnsubmit" />
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
<div ID ="popupform"class="popover">
<div class="alert-danger"> Please Fix The errors </div>
</div>
}
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$(function () {
debugger;
// when the modal is closed
$('#mymodel').on('hidden.bs.modal', function () {
// remove the bs.modal data attribute from it
$(this).removeData('bs.modal');
// and empty the modal-content element
$('#mymodel .modal-content').empty();
});
});
});
</script >
Please help anyone how to popup partial view, once controller return partial view
From Task<ActionResult > to Task<PartialViewResult> then change your ActionLink to RenderPartial.
It should work fine.
Change the return type of your action to Task<PartialView>

return 2 values to controller, text remains NULL

trying to pass 2 values back to the controller id', and 'text'...id passes ok but text always returns nulll any idea why?
<div class="modal-body">
<input type="hidden" id="AlertFreeTextId" name="AlertFreeTextId" value="#Model.AlertFreeTextId" />
<input type="hidden" id="Text" name="Text" value="#Model.Text" />
<div class="form-group">
#Html.LabelFor(x => x.Text)
#Html.TextAreaFor(x => x.Text, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.Text)
</div>
<div>
<a href='#Url.Action("CreateAlertFreeText", "AlertFreeText", new { id = Model.AlertFreeTextId, text = Model.Text})'>
<button class="btn btn-primary">#T("Save")</button>
</a>
</div>
</div>
//controller
public ActionResult CreateAlertFreeText(int id, string text)
{
}
This line here:
<a href='#Url.Action("CreateAlertFreeText", "AlertFreeText", new { id = Model.AlertFreeTextId, text = Model.Text})'>
All this is doing is getting the text that was passed into the View. I assume when you call the view, Model.Text is null, so that's exactly what it's returning.
You need to pull the data from the form when you submit like that.
I'd suggest creating either using a form post, or calling a jquery method to do the post where you can pull the form data.
Maybe something like this: (warning: untested!)
<div class="modal-body">
<input type="hidden" id="AlertFreeTextId" name="AlertFreeTextId" value="#Model.AlertFreeTextId" />
<input type="hidden" id="Text" name="Text" value="#Model.Text" />
<div class="form-group">
#Html.LabelFor(x => x.Text)
#Html.TextAreaFor(x => x.Text, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.Text)
</div>
<div>
<a href='#' id='alertFreeTextLink'>
<button class="btn btn-primary">#T("Save")</button>
</a>
</div>
</div>
<script>
$(document).ready(function() {
$("#alertFreeTextLink").click(function() {
var url = '#Url.Action("CreateAlertFreeText", "AlertFreeText",
new { id = Model.AlertFreeTextId })';
url = url + "&text=" + $("#Text").val();
$.ajax({
url: url
})
.done(function(response) {
/// Do something here
});
});
});
</script>

Categories