Seems like there are a lot of ways to solve this problem.
Currently I make a partial view with a form like so:
<div id="container">
<form id="some-form">
<input id="some-text" type="text">
<input id="some-submit" type="submit">
</form>
</div>
then I hijack the submit with JQuery and do an ajax post and replace the form with another partial view:
$(function()
{
$('#some-form').submit(function(){
$.ajax({
type: "POST",
url: "/Controller/Action",
data: {someVal: $('#some-text').val()},
dataType: "html",
success: function (result) {
$('#container').html(result);
},
error: function (request, status, error) {
alert('Oh no!');
}
});
});
});
The controller would be like:
[HttpPost]
public ActionResult SomeAction(string someVal)
{
//Do something with text
return PartialView("SubmitSuccess");
}
My Question
What are other ways to accomplish the same thing and what are the pros and cons vs what I am doing?
开发者_如何学GoIs Ajax.Form useful?
Personally I use the jquery form plugin. It will make your code shorter. Also assign the action parameter to your form to avoid hardcoding it in your scripts.
<div id="container">
<% using (Html.BeginForm("action", "controller", FormMethod.Post,
new { id = "some-form" })) { %>
<input id="some-text" type="text">
<input id="some-submit" type="submit">
<% } %>
</div>
And then attach the plugin to this form to AJAXify it:
$(function() {
$('#some-form').ajaxForm({
success: function(result) {
$('#container').html(result);
},
error: function(request, status, error) {
alert('Oh no!');
}
});
});
The plugin will automatically send an AJAX request to the action, using the verb specified in the method parameter and serializing the values of all input fields in the request.
What's wrong with the way that you are doing? I've done it that way, and it works out for me. It depends how reusable you need to make the process; you could use a DIV with a css class, and then create a JQuery plugin or widget if you need reusability.
HTH.
精彩评论