All,
I am trying to implement a ternary with a #using statement, in order to switch out the #enctype for certain cases, defined in my ternary. I am getting a Razor parse error stating that I am missing a closing "}" in my #using statement. This error is misleading because all of my curly braces match up fine. I am including the entire form since I cannot see any obvious issues with the syntax in the ternary section.
It looks like the issue is the if/else block but not sure why......
Any ideas why this is problematic? A better way?
#using(Ajax.BeginForm("ProcessCompose",
"ClubOpeningTool",
FormMethod.Post,
new AjaxOptions { UpdateTargetId = "update_panel" },
new { enctype = (fileAttachmentUnsupported ? "application/x-www-form-urlencoded" : "multipart/form-data"),
id = "ComposeForm" }))
{
#Html.ValidationSummary(true)
<fieldset style="width:90%">
<p class="required"><strong>* Required</strong></p>
<div id="update_panel"></div>
<div>
<span style="font-weight:bold; font-size:14px; color:#000000;">To:</span>
</div>
<div>
<table id="compose" class="table-grid">
<tr>
<td><strong>Available #(isTeam? "Team Mambers": Model.Mode)</strong> <br />
#Html.ListBox("AvaliableRecipients", Model.AvailabeRecipients, new{#class="ncb-listbox"})
</td>
<td><button id="addAllRecipient" type="button">>></button><br /><button id="addRecipient" type="button">> </button><br /><button id="removeRecipient" type="button">< </button><br /><button id="removeAllRecipient" type="button"><<</button>
<script type="text/javascript">
$(function () {
$('#addRecipient').click(function () {
$('#AvaliableRecipients option:selected').appendTo('#Recipients');
});
$('#addAllRecipient').click(function () {
$('#AvaliableRecipients option').appendTo('#Recipients');
$("#Recipients option").attr("selected", "selected");
});
$('#removeRecipient').click(function () {
$('#Recipients option:selected').appendTo('#AvaliableRecipients');
});
$('#removeAllRecipient').click(function () {
$('#Recipients option').appendTo('#AvaliableRecipients');
});
});
$("form").submit(function () {
$('#Recipients').find("option").attr('selected', 'true');
});
</script>
</td>
<td><strong>Current Recipients</strong> <span class="required">*</span><br />
#Html.ListBox("Recipients", Model.Recipients,new{#class="ncb-listbox"})<br /><span class="messageBottom">#Html.ValidationMessageFor(model => model.Recipients)</span>
</td>
</tr>
</table>
</div>
<div>
#Html.LabelFor(model => model.Subject) <span class="required">*</span>
</div>
<div>
#Html.EditorFor(model => model.Subject)<br />
<span class="messageBottom">#Html.ValidationMessageFor(model => model.Subject)</span>
</div>
#if (!fileAttachmentUnsupported)
{
<div>
<label>
File Attachment #Html.DisplayFor(model => model.FileName)
</label> <i>(9MB file size limit)</i>
</div>
<input class="js-file-text" type="text" id="fileUploadFileName" name="fileUploadFileName">
#Html.TextBoxFor(model => model.FileAttachment, new {type = "file", #class = "js-file-field"})
<a class="btn blue js-file-btn">Browse</a>
}
else
{
<div>
<label>
<b>Attachment feature not available for Internet Explorer 10 (IE10 or earlier)</b>
</label>
</div>
}
#Html.HiddenFor(model => model.EmailID)
#Html.HiddenFor(model =>model.NewClubId)
#Html.HiddenFor(model =>model.Mode)
#Html.HiddenFor(m => m.DraftOrSentViewMode)
<div>
#Html.LabelFor(model => model.Body) <span class="required">*</span>
</div>
<div>
#Html.TextAreaFor(model => model.Body)<br />
<span class="messageBottom">#Html.ValidationMessageFor(model => model.Body)</span>
</div>
<p>
<input type="submit" id="btnComposeSend" name="Command" value="Send" class="btn blue saveSend"/>
#if (! isTeam) {
<input id="btnComposeSave" type="submit" name="Command" value="Save" class="btn blue saveSend"/>
}
</p>
</fieldset>
}
Not sure why this isn't working, maybe post the whole view? Having said that, if it was me, I would try this...
#using(Ajax.BeginForm(
"ProcessCompose",
"ClubOpeningTool",
FormMethod.Post,
new AjaxOptions { UpdateTargetId = "update_panel" },
new { #enctype = (fileAttachmentUnsupported ? "application/x-www-form-urlencoded" : "multipart/form-data"), id = "ComposeForm" }))
{ ... }
The problem was being caused by an unclosed input tag in the if/else block. Not sure why intellisense did not pick this up or why the error message was seemingly unrelated to the actual problem. Thanks everyone
Before
<input class="js-file-text" type="text" id="fileUploadFileName" name="fileUploadFileName">
After
<input class="js-file-text" type="text" id="fileUploadFileName" name="fileUploadFileName" />
Related
I need to run Partial View from action method as a child action method but it redirect me to another view.
1- I tried to use Html.Action("myAction","myController") and I use [ChildActionOnly] data annotation but without any benefit
2- I tried to use Html.RenderAction("myAction", "My Controller") and I change the action method as PartialViewResult and return PartialView("View", myData) but without any benefit.
3- I tried to use JQuery AJAX but without any benefit also.
What I get
What I Expect
** This is the controller
[Authorize(Roles = "Admin")]
[HttpPost]
[ChildActionOnly]
public ActionResult _GetUserRoles(string UserName)
{
SqlParameter param1 = new SqlParameter("#UserName", UserName);
try
{
IList<GetUserRolesViewModel> roles = Identitydb.Database.SqlQuery<GetUserRolesViewModel>("admin.sp_GetUserRoles #UserName",
((ICloneable)param1).Clone()).ToArray().ToList();
return View(roles);
}
catch (Exception ex)
{
ViewBag.Error = ex.ToString();
return RedirectToAction("ErrorSaveData");
}
}
** This is PartialView Code
#model IEnumerable<AMSIdentity.Controllers.GetUserRolesViewModel>
#if (Model == null)
{
<table></table>
}
else
{
<table class="table table-responsive table-striped table-hover table-bordered table-condensed container" style="margin-top: 5%;">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Id)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
</tr>
}
</tbody>
</table>
<br />
#Html.ActionLink("Return Back", "RemoveRoleFromUser", "Manage")
}
** This is Parent Page Code
ViewBag.Title = "RemoveRoleFromUser";
var error = ViewBag.Error as IEnumerable<String>;
}
<h2> Remove role from user </h2>
<ul></ul>
<div class="row container">
<div class="col-md-6">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.Label("Username", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.Editor("UserName", new { htmlAttributes = new { #class = "form-control" } })
</div>
<hr />
#Html.Label("Role Id", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.Editor("RoleId", new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Remove" class="btn btn-default btn-danger" />
</div>
</div>
</div>
}
</div>
<div class="col-md-6">
<div class="row container">
<div class="col-md-12">
<h3> Get user roles </h3>
#using (Html.BeginForm("_GetUserRoles", "Manage", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.Label("Username", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.Editor("UserName", new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Get rules" class="btn btn-default btn-success" id="btnRules"/>
</div>
</div>
</div>
}
</div>
</div>
<div class="row container">
<div class="col-md-12">
#Html.Partial("_GetUserRoles")
</div>
</div>
</div><!--Second Column-->
</div> <!--End of row-->
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
** This is the view Model
public class GetUserRolesViewModel
{
[DisplayName("Username")]
public string Name { get; set; }
[Key]
[DisplayName("Role Id")]
public string Id { get; set; }
}
** This is AJAX Code that i used to run partial view
<script type="text/javascript">
//$(document).ready(function ()
//{
$("#btnRules").click(function (e)
{
var UserName = $("#UserName").val();
$.ajax({
url: '/Manage/_GetUserRoles',
dataType: 'html',
data:{"UserName": UserName},
success: function (data)
{
$('#listRules').html(data);
},
error: function (xhr, ajaxOptions, thrownError)
{
alert('Failed to retrieve rules.');
}
});
});
//});
</script>
** Route Picture
Route Config Picture
I expect to run the Action Method (_GetUserRoles) Partially in the same view of RemoveRoleFromUser.
your return must be a PartialView() and not a view. view() will return a complete view where as PartialView() will return a partial view. So yo need to change your
return View();
to
return PartialView("YourPartialViewName");
and if you need to pass a parameter to your partial view
return PartialView("YourPartialViewName",roles);
if you are rendering a partial view from your View them you can use Html hepler
return PartialView("~/views/ABC/PartialViewName.cshtml", Yourmodel);
I am assuming that your ajax call hits the controller action. And the partial view needs to be placed in the parent view code at-
<div class="row container">
<div class="col-md-12">
#Html.Partial("_GetUserRoles")
</div>
</div>
Based on these assumptions, you need to change few things in your code:
return PartialView instead of View from the action. Something like this:
return PartialView("_GetUserRoles", roles);
// the partial view name mentioned here is just a sample based on the context.
//You need to give your partial view's name here.
add an id attribute to the div inside which you have written #Html.Partial("_GetUserRoles"). Something like this:
<div class="row container">
<div class="col-md-12" id="userRoles">
</div>
</div>
within the success function in the ajax method, you need to use the id attribute set in above step and populate the data inside it. Something like this:
success: function (data)
{
$('#userRoles').html(data);
}
Install the Microsoft.Jquery.Unobtrusive.Ajax and Microsoft.Jquery.Unobtrusive.Validation in your project. Then add the reference of these two within your view file. Something like this:
#section scripts{
#Scripts.Render("~/Scripts/jquery{version}.js")
#Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
}
This way you should be able to see the partial view within your existing view itself.
Here is the answer
I use ViewData[""] rather than PartialView and i put one parameter in the same action result to check which view i will use.
** Action Method RemoveRoleFromUserConfirmed
public ActionResult RemoveRoleFromUserConfirmed(string UserName, string RoleId, string btnval)
{
if (btnval == "Remove")
{
if (UserName == null && RoleId == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
SqlParameter param1 = new SqlParameter("#RoleId", RoleId);
SqlParameter param2 = new SqlParameter("#UserName", UserName);
try
{
Identitydb.Database.ExecuteSqlCommand("admin.sp_RemoveUserFromRole #RoleId, #UserName", param1, param2);
}
catch (Exception ex)
{
ViewBag.Error = ex.ToString();
return RedirectToAction("ErrorSaveData");
}
return RedirectToAction("Roles");
}
else if (btnval == "Get Rules")
{
SqlParameter param1 = new SqlParameter("#UserName", UserName);
try
{
IList<GetUserRolesViewModel> roles = Identitydb.Database.SqlQuery<GetUserRolesViewModel>("admin.sp_GetUserRoles #UserName",
((ICloneable)param1).Clone()).ToArray().ToList();
string result = "";
foreach (var item in roles)
{
result += "<tr>"
+ "<td>" + item.Name + "</td>"
+ "<td>" + item.Id + "</td>"
+ "</tr>";
}
ViewData["getrules"] = result;
return View();
}
catch (Exception ex)
{
ViewBag.Error = ex.ToString();
return RedirectToAction("ErrorSaveData");
}
}
return View();
}
** This is the view
#{
ViewBag.Title = "RemoveRoleFromUser";
var error = ViewBag.Error as IEnumerable<String>;
}
<h2> Remove role from user </h2>
<ul></ul>
<div class="row container">
<div class="col-md-6">
#using (Html.BeginForm("RemoveRoleFromUser", "Manage", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.Label("Username", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.Editor("UserName", new { htmlAttributes = new { #class = "form-control" } })
</div>
<hr />
#Html.Label("Role Id", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.Editor("RoleId", new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Remove" name="btnval" class="btn btn-default btn-danger" />
</div>
</div>
</div>
}
</div>
<div class="col-md-6">
<div class="row container">
<div class="col-md-12">
<h3> Get user roles </h3>
#using (Html.BeginForm("RemoveRoleFromUser", "Manage", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.Label("Username", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.Editor("UserName", new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Get Rules" name="btnval" class="btn btn-default btn-success" id="btnRules" />
</div>
</div>
</div>
}
</div>
</div>
<div class="row container">
<div class="col-md-12" id="listRules">
<!--Data Come from ViewData-->
<table class="table table-responsive table-striped table-hover table-bordered table-condensed container" style="margin-top: 5%;">
<thead>
<tr>
<th>
Role Name
</th>
<th>
Role Id
</th>
</tr>
</thead>
<tbody>
#Html.Raw(ViewData["getrules"])
</tbody>
</table>
</div>
</div>
</div><!--Second Column-->
</div> <!--End of row-->
<div>
#Html.ActionLink("Back to List", "Roles")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
I put the name of button same in two buttons (remove and get rules)
after that i checked the value of the button in ActionMethod and if it
is remove it will do some function and if it is get rules i will use
ViewData[""] to put the view.
Regards,
Ali Mosaad
Software Developer
I would suggest changing
return View(roles);
to
return PartialView(roles);
or
return PartialView("_GetUserRoles", roles);
Using ajax
$.ajax({
url: '/Manage/_GetUserRoles',
dataType: 'html',
data:{"UserName": UserName},
success: function (data)
{
$('#listRules').html(data);
},
error: function (xhr, ajaxOptions, thrownError)
{
alert('Failed to retrieve rules.');
}
});
...
<div class="row container">
<div id="listRules" class="col-md-12">
#Html.Partial("_GetUserRoles", Model.Roles)
</div>
</div>
This form searches for the value passed into "searchString" into a table and returns all the selected values.
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="text" name="searchString" />
<input type="submit" value="Search" class="btn btn-default" />
</div>
</div>
</fieldset>
}
This form is supposed to provide an "ActionLink" which will be clicked after a search is made and I want the action link to pass the previously searched string "searchString", when the link is clicked but it is sending an empty string.
<table class="table">
<tr>
<th>
#Html.ActionLink("Author", "Index", "Home", new { searchString = Html.Name("searchString").ToString()}, null)
</th>
</tr>
</table>
How do I retain the value of original search string "searchString" in this "ActionLink"? Both forms go to the same method Index().
function MyFunc()
{
if (($('#searchString').val()).length > 0) {
var url = "/Home/Index?SearchTerm=" + $('#searchString').val();
window.location.href = url;
}
else
{
alert('please enter value for search');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="text" name="searchString" id="searchString" />
<input type="submit" value="Search" class="btn btn-default" />
</div>
</div>
</fieldset>
<table class="table">
<tr>
<th>
<a href onclick="MyFunc()">Search</a>
</tr>
</table>
Please use this.
#Html.Action("Controller","actionName", new { searchString = "searchString" })
the other way is this
var searchString="abc";
#Html.Action("Controller","actionName", new { searchString = searchString })
You can send it by like variable through your controller :
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="text" name="searchString" value="#ViewBag.SearchString"/>
<input type="submit" value="Search" class="btn btn-default" />
</div>
</div>
</fieldset>
}
your controller should be like this
public ActionResult Search(string searchString)
{
ViewBag.SearchString = searchString; // This line send your string back to your view
return View();
}
for the link the same is applicable
<table class="table">
<tr>
<th>
#Html.ActionLink("Author", "Index", "Home", new { searchString = ViewBag.SearchString}, null)
</th>
</tr>
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.
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>
I have a problem with calling JS method from form in MVC3 project: I have a "search"page without forms with two buttons - Search and Cancel. Click on search runs JS function runSearch in ProductDefinition.
<div id="productSearch-dialog" class="modal fade" style="width: 1000px; display: none">
<div class="modal-header">
<button class="close" aria-hidden="true" data-dismiss="modal" type="button">×</button>
<h3>Search Results</h3>
</div>
<div class="modal-body" style="height: 650px;">
<div>
<input id="inputname" type="text" /><font class="red-font" id="lblrequired" style="display: none">*</font>
</div>
<div id="searchresultcontain" class="grid">
</div>
<div id="Pagination" class="pagination">
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" onclick="productDefinition.runSearch();">Search</button>
<button class="btn btn-primary" data-dismiss="modal">Cancel</button>
</div>
How can I run this JS method (runSearch) when I press ? As far as I understand, this will be onsubmit event which is form event, so I am need to add form element with onsubmit property. I tried surrounding input field with BeginForm helper method:
#using (Html.BeginForm(new { onsubmit = "productDefinition.runSearch();" }))
{
<input id="inputname" type="text" /><font class="red-font" id="lblrequired" style="display: none">*</font>
<input type="submit" value="Submit" style="visibility: hidden" />
}
but it does not seem to be working - when I press enter I for some reason get source of the page and arrive at localhost/?onsubmit=productDefinition.runSearch() URL.
What can be the source of the problem and how can I get the same behaviour for onsubmit as for onclick?
#using (Html.BeginForm(new { onsubmit = "return runSearch();" }))
<script type="text/javascript">
function runSearch() {
// your logic to perform the search.
return true;
}
</script>
You need to use the following version of BeginForm method in order to specify html attributes.
However, it is considered a bad practice to use inline javascript so I would suggest to assign and id attribute to your form and handle its submit event in the external javascript file instead. If you are using jQuery for your project, here is a good example from their docs - http://api.jquery.com/submit/. In plan JavaSCript it is a bit more tricky but still easy to do.
#model Models.Person
<script type="text/javascript">
$(document).ready(function () {
$('#registerInputId').click(function () {
alert('what do you do before send? For example encrypt the password');
$('#Password').val(CryptoJS.MD5($('#Password').val()));
})
});
</script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal" style="display: inline-block; margin: 5% auto;">
<div style="font-size: 18px; margin-right:2px; margin-bottom:20px; text-align:right;">Add form</div>
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-5" })
<div class="col-md-7">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-5" })
<div class="col-md-7">
#Html.EditorFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</div>
</div>
<div class="form-group" style="margin-top: 30px;">
<div class="col-md-offset-3 col-md-6">
<input id="registerInputId" type="submit" value="Register" class="btn btn-default" />
</div>
</div>
</div>
}
Form.Id is required if onsubmit handler implements generic functionality, applicable for multiple forms. (example : disabling all input fields)
Form
#using (Html.BeginForm(new {
id = "form24",
onsubmit = "return onSubmitHandler(id);"
}))
handler
<script type="text/javascript">
function onSubmitHandler(formId) { /*formId is form24 */ }
</script>