I am using MVC 3 Razor. I have 2 submit buttons on my view the problem i m having is both submit buttons cause the validation of the model. I want to hook up indivi开发者_StackOverflow中文版dual submit buttons with specific input controls for validation.
Add this class to your project:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class ButtonClickAttribute : ActionNameSelectorAttribute
{
public string Name { get; set; }
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
return controllerContext.HttpContext.Request[Name] != null;
}
}
In view:
<input type="submit" value="Connect to server" name="connect" />
In controller:
[HttpPost]
[ButtonClick(Name = "connect")]
public ActionResult Connect(ServerAddressModel model) {...
Ok, I've been testing around and indeed, if you have several fields marked as required
on your model but you want to post your model through multiple forms, every submit button will trigger validation.
An option for you would be to trigger the jQuery validation manually, so, what you could do is make those submit buttons normal buttons, ie:
<input id="button1" type="button" value="Submit" />
and then attach click events to those buttons and trigger the validation in there:
$("#button1").click(function() {
$("#form1").validate(); // assumes a form with id="form1"
// post the form here
});
You'd do the same for the other button/form.
I'd recomment taking a look a the jQuery Form plugin, by the way. Among other things, it defines a beforeSubmit
event that you coudl use to trigger the validation.
NOTE to all: This is not my original answer, I've changed it completely after some back and forth in the comments and some testing on my side.
Here is a link to a blog post by Steve Sanderson which I used when playing with multiple forms on a single view.
Partial Validation in ASP.NET MVC 2
精彩评论