This question has been asked before, but none that I have reviewed give a clear or complete solution. I hope you can help me here.
I want to pass data entered from the client (an input text field) to the server using AjaxHelper. If there’s a more elegant solution, please respond with code that is relevant to my sample.
I have also tried using the Ajax.BeginForm() with no success. Keep in mind that there are TWO buttons here. One that dynamically appends what the user enters below the input field. And the second button is just a simple non-ajax post to the controller.
The items are dynamically appended using the Ajax.ActionLink() and a partial view “_NewRow.cshtml” to define the markup.
Here’s my Index.cshtml:
@model MyAccount
@using (Html.BeginForm())
{
@Html.ValidationSummary(excludePropertyErrors: true)
<fieldset>
<div class="form-element cf">
<div class="form-label">
<span>Approvers:</span>
</div>
<div class="form-input cf">
@Html.TextBox("accountName", string.Empty, new { @class = "input-search-person" })
@Ajax.ActionLink("Add", "AddRecipient", "Test",
new
{
accountName = "Value from Input here."
},
new AjaxOptions
{
UpdateTargetId = "recipientList",
HttpMethod = "POST",
InsertionMode = InsertionMode.InsertAfter
})
<div style="display: block; margin-top: 5px">
<div id="recipientList">
</div>
</div>
</div>
</div>
</fieldset>
<input type="submit" class="btn green rounded" id="Submit" name="Submit" value="Submit" />
}
Here’s my TestController.cs:
public class TestController : Controller
{
public PartialViewResult AddRecipient(string accountName)
{
MyAccount acct = new MyAccount();
acct.LastName = accountName;
acct.Email = "some email";
return PartialView("_NewRow", acct);
}
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(IEnumerable<string> accountList, string accountName)
{
if (Request.IsAjaxRequest())
{
MyAccount acct = new MyAccount();
acct.LastName = accountName;
acct.Email = "some email";
return PartialView("_NewRow", accountName);
}
if (ModelState.IsValid)
{
RedirectToAction("AnotherAction", "AnotherController");
}
return View();
}
}
Here’s my Partial View “_NewRow.cshtml”:
@model MyAccount
@using (Html.BeginCollectionItem("recipients"))
{
@Html.HiddenFor(model => model.LastName)
@Html.HiddenFor(model => model.Email)
<span>@Model.LastName<span>(@Model.Email)</span></span>
}
And here’s my simple model MyAccount.cs:
[Serializable]
[DataContract]
public class MyAccount
{
[DataMember]
public virtual string LastName { get; set; }
[DataMember]
public virtual string Email { get; set; }
}
Your help would be greatly appreciated.
Thank you!
Change Your Action Link to a regular html button
Then with a little bit of jQuery you are done