1

I have the following file input tag in the "Create" View:

<input type="file" id="RequestFile" name="RequestFile"/>
@Html.ValidationMessage("RequestFile")

The ViewModel contains this corresponding property:

[Required(ErrorMessage="Please select a file")]
public HttpPostedFileBase RequestFile { get; set; }

This works fine in the "Create" View, but in the "Edit" View, I get ModelState.Isvalid as false. Using the same ViewModel I would like to exclude this field from validations because I would not want to upload the file again.

I tried simply disabling the input tag like this:

<input type="file" id="RequestFile" name="RequestFile" disabled/>            

This has a disabled input control but the Validation still fired.

Also applying the BindAttribute in the Controller did not work (see this Question)

Ideally (I know it sounds unlikely), if there is a server-side solution to this, please post your thoughts. If there is a small client-side trick, please let me know!

4

2 回答 2

2

最好的方法是完全删除该属性,并始终直接从表单集合中访问它(并手动验证它)或使用属性名称手动删除模型状态错误(正如@cheesemacfly 在他的评论中所说的那样ModelState.Remove("RequestFile"))。后者使得它很容易修复。

于 2012-12-21T02:23:58.623 回答
0

您可以使用 form.onsubmit 来检查它 document.getElementById("RequestFile").value 是否为空/空,如果是则取消提交。

就像是

<form onsubmit="if(!document.getElementById('RequestFile').value){alert('Please select a file.');return false;}" >
<input type="file" id="RequestFile" name="RequestFile" />
<input type="submit"/>
</form>

return false 取消提交。

http://jsfiddle.net/Cg7HY/1/

或者放在提交按钮本身的点击事件中

http://jsfiddle.net/Cg7HY/3/

于 2012-12-21T02:26:00.210 回答