i have four different forms on my page and each are ajax forms.
I’m sending post request for first form with ajax to MVC Controller, it basically returns ViewData[“TEST”] back to me.
I want to use ViewData on my view and i need set this to a hidden field for use other forms.
How i can reach it without using normal submit ?
Here is my code:
@using (Ajax.BeginForm("Index", new AjaxOptions{ HttpMethod = "POST" }))
{
<script type="text/javascript"> alert('@(ViewData["TEST"])'); </script>
<input type="text" name="name" />
<input type="button" onclick="javacript:SubmitAjax();" />
}
<script type="text/javascript">
function SubmitAjax() {
$.ajax({
type: 'POST',
data: $("#form0").serialize(),
url: "/Home/Index",
timeout: 2000,
async: false,
success: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(message_Error);
}
});
}
And Controller;
[HttpPost]
public ActionResult Index(string name)
{
ViewData["TEST"] = "TESTSTRING";
return View();
}
No ViewData !!!! . Simply return the content.
and to set this in the hidden field,you can do so int he
successevent of your ajax functionAlso do not hard code the Path to action method like that. Always make use of the HTML helper methods.
Replace
with
I personally prefer to avoid the
AjaxBeginFormmethod and would like to write some clean handwritten javascript code to handle this.EDIT : As per the comment.
If you want to return multiple items, You can return JSON
Ex 2 : returning anonymous type to JSON
Ex 1 : returning a ViewModel to JSON
Assuming you have a class like
Now you can use this class and return it as
JSON